discord 机器人“client.loop.create_task(update_stats())”错误

问题描述 投票:0回答:1

我正在尝试设置一个不和谐的机器人,所以我试图添加

update_stats
函数来从我的服务器获取所有活动数据并将它们保存到
stats.txt
文件中,所以每当我尝试运行该机器人时,我都会保留在
client.loop.create_task(update_stats())

中出现错误
import os
import time
import asyncio
import discord
from discord import app_commands
from discord.ui import button, view
from discord.ext import commands, tasks

# id = client id

TOKEN = 'my token'
GUILD = "guild id"

messages = joined = 0
intents = discord.Intents.default()
intents.message_content = True
client = discord.Client(intents=intents)

async def update_stats():
    await client.wait_until_ready()
    global messages, joined

    while not client.is_closed():
        try:
            with open("stats.txt", "a") as f:
                f.write(f"Time : {int(time.time())}, Messages : {messages}, Members Joined : {joined}\n")

            messages = 0
            joined = 0

            await asyncio.sleep(5)

        except Exception as e:
            print(e)
            await asyncio.sleep(5)

@tasks.loop(seconds=5)
async def auto_send(channel : discord.TextChannel):
    await channel.send("Welcome")

@client.event
async def on_ready():

    if not auto_send.is_running():
        channel = await client.fetch_channel("") # <--- client id
        auto_send.start(channel)
    for guild in client.guilds:
            if guild.name == GUILD:
                break
    print(
        f'{client.user} has successfully connected to the following guild(s):\n'
        f'{guild.name}(id: {guild.id})'
        )
    await client.change_presence(
        activity=discord.Activity(name='anything', type=discord.ActivityType.playing)
    )

@client.event
async def on_member_join(member):
    global joined
    joined += joined
    for channel in member.server.channels:
        if str(channel) == ['general', 'welcome']:
            await client.send_message(f"""Welcome to the server! {member.mention}""")


@client.event
async def on_message(message):
    global messages
    messages +=  1
    id = client.get_guild("client id")
    channels = ["welcome", "mods" ,"general", "bot-commands", "admins"]
    valid_users = ["my username"]

    if str(message.channel) in channels and str(message.author) in valid_users :        
        print(message.content)
        if message.content.find("!hello") != -1:
            await message.channel.send("Hi")
        elif message.content == '!users':
            await message.channel.send(f"""Number of members : {id.member_count}""")
        else:
            print(f"""User : {message.author} tried to do command {message.content} in  #{message.channel} channel!""")

client.loop.create_task(update_stats())
client.run(TOKEN)

我不断收到此错误:

File "C:\Users\.vscode\repo\discord bot\bot2", line 84, in <module>
    client.loop.create_task(update_stats())
    ^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: loop attribute cannot be accessed in non-async contexts. Consider using either an asynchronous main function and passing it to asyncio.run or using asynchronous initialisation hooks such as Client.setup_hook
python discord discord.py bots
1个回答
0
投票

您正在尝试在异步上下文之外访问客户端对象的循环属性。

@client.event
async def on_ready():
    if not auto_send.is_running():
        channel = await client.fetch_channel("") # <--- client id
        auto_send.start(channel)
    
    for guild in client.guilds:
        if guild.name == GUILD:
            break
    print(
        f'{client.user} has successfully connected to the following guild(s):\n'
        f'{guild.name}(id: {guild.id})'
    )
    await client.change_presence(
        activity=discord.Activity(name='anything', type=discord.ActivityType.playing)
    )
    
    # Start the stats update task
    client.loop.create_task(update_stats())

您需要将

client.loop.create_task(update_stats())
放入您的
on_ready
中。

© www.soinside.com 2019 - 2024. All rights reserved.