如何在Discord机器人上使用Python发送.txt文件?

2024-04-27 00:29:13 发布

您现在位置:Python中文网/ 问答频道 /正文

很抱歉问了个基本问题,我是个初学者。因此,我更需要你以正确的方向面对我,而不是为我这样做

我有一个discord bot,它在JS中起作用,但是在尝试从Raspberry Pi全天候运行它时,只需将其转换为Python就更容易了。原始的JS代码是功能性的,可以用我下载要观看的内容列表作为.txt文件响应!movies!TV。我有一系列的.bat文件,它们定期编译列表,并将其scp/ssh到我的Pi中。因此.txt文件位于我的Pi上。我可以让Python版本用文本回复来响应!movies,但无法确定是否发送本地.txt文件。我能找到的任何指南都是基于代码创建的.txt文件。我所需要的帮助是使send函数发送.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文件,提前谢谢


Tags: 文件代码文本importtxtsend列表bot
1条回答
网友
1楼 · 发布于 2024-04-27 00:29:13

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

相关问题 更多 >