【问题标题】:discord.py wait_for not working in a methoddiscord.py wait_for 在方法中不工作
【发布时间】:2021-07-03 18:36:08
【问题描述】:

在这种情况下,我有 2 个单独的文件,其中 1 个用于主文件,另一个是包含函数的文件(不在 Cog 中)。我想让用户回复机器人输出的消息,然后机器人将该消息发送回聊天。

这里的问题是程序没有注册一个人输入的消息,我尝试使用self.bot 或client 而不是只使用机器人来实现wait_for 功能,但这不起作用。

这是我的main.py 文件的代码

import discord
import asyncio
from discord.ext import commands
from anime import *
from embed import *

bot = commands.Bot(command_prefix="m.")

TOKEN = "INSERT TOKEN HERE"

@bot.event
async def on_ready():
    print("Connected to discord")

@bot.command(name="searchanime", help="Seaches through the MAL Database to find an anime. Requires a Title to search")
async def search(ctx, *, query):
  await search_anime(ctx, query)

bot.run(TOKEN)

这是我的 anime.py 代码,它是一个单独的文件

import discord
import requests

headers = {
    'x-rapidapi-key': "2ed26cb89emsh2b7cb079ec42fd9p15290cjsne485ef05078a",
    'x-rapidapi-host': "jikan1.p.rapidapi.com"
}

async def search_anime(ctx, query):
    url = "https://jikan1.p.rapidapi.com/search/anime"
    querystring = {"q": query, "format": "json"}
    response = requests.request("GET", url, headers=headers, params=querystring).json()

    response_list  = []
    for i in range(4):
        response_list.append(response["results"][i])

    await ctx.send("Message 'm.(desired number)' without the parenthesis to select the anime you are looking for from this list")
    for i in range(len(response_list)):
        await ctx.send(f"{i+1}) {response_list[i]['title']}")
    
    try:
        msg = await bot.wait_for("message")
        if msg:
            await ctx.send(msg.content)
    except asyncio.TimeoutError:
        await ctx.send("Cancelling due to timeout")

【问题讨论】:

  • 您没有在anime.py 中声明“bot”变量,而只是在main.py 中声明。你可以在main.py中定义那个函数,这样会更好。

标签: python discord discord.py python-asyncio


【解决方案1】:

bot 根本没有在你的anime.py 中定义,你可以将它作为参数传递给函数。

await search_anime(bot, ctx, query)
async def search_anime(bot, ctx, query)
   #other stuff

【讨论】:

  • 感谢您的回答,成功了!作为后续,简单地创建一个 cog 这样我就不必传递这么多参数会更有效吗?
  • cogs 是为了同样的目的而引入的。
猜你喜欢
  • 1970-01-01
  • 2021-09-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-27
  • 2021-02-06
  • 2019-07-10
相关资源
最近更新 更多