gpt4 book ai didi

python - 从另一个文件调用函数 - Discord bot

转载 作者:行者123 更新时间:2023-12-01 06:23:55 24 4
gpt4 key购买 nike

我不熟悉 Discord 机器人或 Python 的大部分内容,所以这是一个我无法找出答案的简单问题。

我有两个文件; Discord_bot.py 和 test.py如何从 test.py 转发消息以将其发送到 Discord 中的 channel ?

测试.py

import discord_bot

discord_bot.signal(msg = "Hi")

discord_bot.py

import discord
from discord.ext import commands

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

@bot.command()
async def signal(ctx, *, msg):
await ctx.send(msg)

Discord 机器人工作正常,但从测试中调用信号函数并不是正确的方法。请问这里有什么帮助吗?

最佳答案

需要解开的内容有很多。

<强>0。切勿在线发布您的 Discord token 。如果您的 token 在线发布,Discord 可能会自动使其失效。

<强>1。您目前尚未运行机器人,请在末尾添加 bot.run(TOKEN)

<强>2。 Discord 机器人扩展的命令如何工作

@bot.command()decorator ,如果您不知道它们是如何工作的,请阅读它。过于简化,它们会获取您的函数并在机器人中注册

commands 扩展的内部工作原理基本上是:

  1. 通过加载装饰器来注册所有命令
  2. 每当消息到达时,检查它是否包含前缀,如果包含,则检查它是否适合命令。
  3. 如果 2 中的两项检查都通过,则构造 Context对象,然后将该对象传递给函数。类似于以下内容:
signal(ctx, *args)

这就是 ctx 对象不能定位的原因,因为该函数在机器人内部工作中作为普通参数调用的方式。

<强>4。不要尝试创建自己的上下文对象,除非您知道自己在做什么。只有在覆盖默认消息解析器时才需要创建上下文对象。

<强>5。不要为此使用命令。

据我所知,你想做什么:自己调用命令。这很简单:

文件 1:

@bot.command()
async def signal(ctx, *, msg):
print(msg)

文件2:

from file1 import signal
import asyncio # if you don't know asyncio, read up on it

asyncio.run(signal(None, 'This is an argument'))

这很容易工作,它会打印你的东西。但您不希望将其打印出来,对吧?您希望它在 channel 发送。这就是你需要上下文对象的原因,我之前说过,不要自己构建。那么我们实际上如何做到这一点呢?

答案是:不要使用命令。它们用于对消息使用react,而不是由它们自己调用。

<强>6。您(可能)想要的解决方案

所以这里的主要变化是:

  1. 信号现在是一个没有装饰器的普通异步函数

  2. 我们实际上指定了一个 channel ,我们希望将内容作为函数的参数发送到该 channel

文件 1:

import discord
from discord.ext import commands

TOKEN = 'do not share your token online'
bot = commands.Bot(command_prefix='!')

# as the channel_id, pass the channel_id you want the message to be sent in
async def signal(msg, channel_id):
global bot # getting our bot variable from the global context
channel = bot.get_channel(channel_id)
await channel.send(msg)

bot.run(TOKEN)

这里的主要变化是:

  1. 我们使用 asyncio.run 来调用该函数。异步函数无法使用常规语法调用。
  2. 您可能需要运行 file2.py 来启动该程序。运行 file1 将不会加载 file2。

文件2

from file1 import signal
from time import sleep
import asyncio

sleep(5) # We need to give our bot time to log in, or it won't work
asyncio.run(signal('hi!', 123))

关于python - 从另一个文件调用函数 - Discord bot,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60254002/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com