如何让我的不和谐机器人从 .txt 文件(python)发送消息

时间:2021-02-26 11:14:58

标签: python discord bots

import discord
import os

from keep_alive import keep_alive

client = discord.Client()


@client.event
async def on_ready():
    print('Logged in as {0.user}'.format(client))


@client.event
async def on_message(message):
    if message.author == client.user:
        return
#!test1
    if message.content.startswith('!test'):
        await message.channel.send("<@471653134440071168> tag test")

client.run('my token')

keep_alive()
token = os.environ.get("DISCORD_BOT_SECRET")
client.run(os.getenv('my token'))

这是我的代码,我想要做的是创建一个包含 "<@471653134440071168> tag test" 消息的 .txt 文件,让我的机器人读取它并将该消息发送到文本通道。

PS:我是 Discord 机器人和 Python 的新手

1 个答案:

答案 0 :(得分:0)

您可以创建此命令来发送您想要的任何文件。

@client.command()
async def test(ctx):
    with open('name.txt', 'r') as f: #if you have the file in another folder use the path instead of just the name
        msg = f.read()
        await ctx.send(msg)

如果你想把它作为活动来做就这样

@client.event
async def on_message(message):
    if message.author == client.user:
        return
    if message.content.startswith('!test'):
        with open('name.txt', 'r') as f:
           msg = f.read()
           await ctx.send(msg)
    #await bot.process_commands(message)

请记住,如果您将来向机器人添加任何命令,则应添加 await client.process_commands(message),否则它将仅运行第一个事件。

相关问题