首页 > 解决方案 > 如何在 Discord Bot 上使用 Python 发送 .txt 文件?

问题描述

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

我有一个可在 JS 中运行的不和谐机器人,但在尝试从 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文件,提前谢谢您。

标签: pythonraspberry-pidiscordbots

解决方案


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. 上传图片

推荐阅读