繁体   English   中英

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

[英]How can I make my discord bot send messages from a .txt file (python)

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 的新手

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

@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) ,否则它将仅运行第一个事件。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM