如何在 Discord Bot 上使用 Python 发送 .txt 文件?

时间:2021-02-21 08:31:18

标签: python raspberry-pi discord bots

对不起,我是个初学者。因此,我更需要你以正确的方向面对我,而不是为我做。

我有一个可在 JS 中运行的 discord 机器人,但在尝试从 Raspberry Pi 24/7 运行它时,将其转换为 Python 会更容易。原始的 JS 代码是功能性的,可以响应 !movies!TV,并以 .txt 文件的形式显示我已下载观看的内容列表。我有一系列 .bat 文件,它们定期编译列表并将其 scp/ssh 发送到我的 Pi。因此 .txt 文件位于我的 Pi 上。我可以让 Python 版本通过文本回复响应 !movies,但无法确定发送本地 .txt 文件。我能找到的任何指南都基于代码创建的 .txt 文件。我需要帮助的只是让发送函数发送 .txt 文件而不是短信,这是我的代码:

import discord

from discord.ext 

import commands

bot = commands.Bot(command_prefix='!')


@bot.command(pass_context=True)

async def movies(ctx):
    
await ctx.send("Here ya go:")
    
bot.run('***MYTOKEN***')

如前所述,这段代码是完全函数式的,我必须学习哪些函数才能发送.txt文件,在此先感谢您。

1 个答案:

答案 0 :(得分:0)

discord.py 直接支持文件

with open('my_file.txt', 'r') as fp:
    await ctx.send(file=discord.File(fp, 'new_filename.png'))

或者,如果您想发送文件的内容

with open('my_file.txt', 'r') as fp:
   await ctx.send(fp.read()) # wont work if number of characters is greater than 3000

参考资料

  1. Uploading an image
相关问题