【问题标题】:Discord.py bot is not accepting variables in async functionDiscord.py bot 不接受异步函数中的变量
【发布时间】:2020-11-29 07:21:09
【问题描述】:

我正在尝试编写一个机器人,它从 mee6 的 API 中获取数据,并将版主角色分配给排行榜的前 3 名。我也得到了这些人的用户 ID,但现在我无法将这些用户放入参数中并赋予这些用户角色。

我尝试使用一些事件来做到这一点,但我没有找到适合我在消息事件中所做的事情。如果您对此有任何其他解决方案,那将非常有帮助。

我是 Python 初学者,不知道如何有效地使用 API 或编写好的 Python 代码。

代码:

import requests
import json
import discord
from discord.ext import commands, tasks
from discord.utils import get

class applicable_members:

    #Variables
    member={}
    mee6API = "https://mee6.xyz/api/plugins/levels/leaderboard/766213304141086731?limit=999&page=0"

    #Gets the data from api
    result = requests.get(mee6API).json()

    #Gets specific data related to members
    players = result.get("players")

    #Loop to form dict of player and their xp
    for player in players:
        member[player.get("xp")] = player.get("id")

    #List of user-id of people illegible to get Mod role
    people = list(member.values())[:3]

class samrid_bot:

    #Variables
    token = "<TOKEN>"
    role_name = "Mods"
    peoples = applicable_members.people

    #Declaring Prefix
    client = commands.Bot(command_prefix=".", case_insensitive=True)


    @client.event
    async def on_ready():
        print("Bot is ready")
    
    ppl = peoples[1]
    
    @tasks.loop(seconds=5.0, count=5)
    async def addrole(person, role_n):
        member = person
        role = role_n
        await client.add_roles(member, role)

    addrole.start(ppl, role_name)

    client.run(token)

错误:

Unhandled exception in internal background task 'add'.
Traceback (most recent call last):
  File "C:\Users\samri\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\ext\tasks\__init__.py", line 101, in _loop
    await self.coro(*args, **kwargs)
  File "c:/Users/samri/OneDrive - Hoffman/Documents/Websites/Discord Bot/Samrids Bot/bot.py", line 52, in add
    await client.add_roles(member, role)
AttributeError: 'Bot' object has no attribute 'add_roles'
Bot is ready

【问题讨论】:

    标签: python python-3.x discord.py discord.py-rewrite


    【解决方案1】:

    on_message 是一个事件监听器,它只接受一个参数messagehttps://discordpy.readthedocs.io/en/latest/api.html#discord.on_message

    每当发送消息时都会执行此操作,消息参数设置为已发送的消息。你不能修改它来接受你自己的参数,这就是代码失败的原因。

    编辑:为了重复它,你最好使用 discord.py 提供的任务循环https://discordpy.readthedocs.io/en/latest/ext/tasks/

    【讨论】:

    • 好的,有什么建议吗?我该怎么做才能让它接受我的论点?
    • 这取决于您想在哪里执行此操作,您的代码不一定需要在侦听器中。所以你可以在外面或 on_ready 里做。
    • 是的,谢谢,我如何让它重复,我需要它每隔一小时左右运行一次?
    • 在这种情况下,不要使用on_ready,只需使用任务循环discordpy.readthedocs.io/en/latest/ext/tasks,我会用它来编辑我的答案
    • 谢谢你帮了我很多
    猜你喜欢
    • 1970-01-01
    • 2023-03-16
    • 1970-01-01
    • 2020-10-28
    • 2019-03-02
    • 1970-01-01
    • 1970-01-01
    • 2020-06-28
    相关资源
    最近更新 更多