【问题标题】:Run discord bot/client from another file从另一个文件运行 discord bot/client
【发布时间】:2021-12-18 16:36:47
【问题描述】:

我怎样才能在一个文件中包含机器人代码,但在另一个文件中运行实际的机器人(不是 cogs/extensions)。 由于循环冲突,我需要在另一个文件中运行它。

我尝试在其上导入客户端(机器人构造函数的变量)和 .start(),但没有成功,只有 Web 服务器启动。

示例代码:

在机器人文件中:

import discord
from discord.ext import commands
client = commands.Bot(command_prefix="!")

@client.event
async def on_ready():
    print("Im ready!")

在另一个文件中(在我的例子中是 Sanic 网络应用程序):

from bot_file import client
import discord
from sanic import Sanic

app = Sanic()

app.run()
client.run("token")

【问题讨论】:

  • 您需要做的是在机器人内部运行 Sanic,或者不在 sanic 内部运行。其中一个必须是主要应用程序,并将用于启动另一个。

标签: python discord.py sanic


【解决方案1】:

我有很酷的解决方案给你 你为什么不只制作一个包含这样所有代码的文件

import discord
import requests
import json

client = discord.Client()

def get_quote():
  response = requests.get("https://zenquotes.io/api/random")
  json_data = json.loads(response.text)
  quote = json_data[0]['q'] + " -" + json_data[0]['a']
  return(quote)

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

@client.event
async def on_message(message):
  if message.author == client.user:
    return

  if message.content.startswith('inspire'):
    quote = get_quote()
    await message.channel.send(quote)

client.run('TOKEN')

【讨论】:

  • 正如目前所写,您的答案尚不清楚。请edit 添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。你可以找到更多关于如何写好答案的信息in the help center
猜你喜欢
  • 1970-01-01
  • 2020-05-31
  • 2021-07-21
  • 2020-08-17
  • 2021-07-13
  • 2019-05-17
  • 2022-07-21
  • 2020-07-02
  • 1970-01-01
相关资源
最近更新 更多