首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >从客户端到机器人的Discord.py切换

从客户端到机器人的Discord.py切换
EN

Stack Overflow用户
提问于 2021-01-23 05:00:02
回答 2查看 362关注 0票数 0

我在制作不和谐机器人方面还是个新手。我已经创建了一个方法来获取机器人所连接到的服务器中所有成员的列表。这种方法可以很好地工作。但是,我也在尝试让机器人接受命令。我在这方面遇到了很多麻烦,我一直认为我应该使用commands.Bot而不是客户端。不过,我不知道如何让我的原始方法与commands.Bot一起工作。任何帮助都将不胜感激!

代码语言:javascript
运行
复制
import os

import discord
import csv
from collections import defaultdict
from discord.ext import commands




intents = discord.Intents.all()
client = discord.Client(intents=intents)
outP = open("giveawayList.txt", "w")
bot = commands.Bot(command_prefix='!')


@client.event
async def on_message(message):
    if message == "!test":
        await message.channel.send("you failed the test")
        
        
@client.event
async def on_ready():
    for guild in client.guilds:
        if guild.name == GUILD:
            break

    print(
        f'{client.user} is connected to the following guild: \n' 
        f'{guild.name} (id: {guild.id})'
    )


    count = 0
    for guild in client.guilds:
        for member in guild.members:
            print(member)
            if 'Bots' not in str(member.roles):
                
                print(member.name, ' ')
                outP.write(member.name)
                outP.write("\n")
                count += 1
    print('Number of members: ' + str(count))
EN

Stack Overflow用户

发布于 2021-01-23 05:36:31

最好使用commands.bot而不是Client,因为它是一个扩展版本,因为它继承了Client的所有功能。

我看到您已经尝试从使用Client迁移到使用commands.bot,但请记住以下几点:

您不希望同时使用这两个工具,因此这是错误的:

代码语言:javascript
运行
复制
client = discord.Client(intents=intents)
bot = commands.Bot(command_prefix='!')

你应该只保留机器人的那个。

除此之外,你还需要替换装饰器中的client和函数内部的调用。更正后的代码应该如下所示:

代码语言:javascript
运行
复制
import os

import discord
import csv
from collections import defaultdict
from discord.ext import commands
    
intents = discord.Intents.all()
outP = open("giveawayList.txt", "w")
bot = commands.Bot(command_prefix='!', intents=intents)
    
@bot.event
async def on_message(message):
    if message == "!test":
        await message.channel.send("you failed the test")

    await bot.process_commands(message)
            
@bot.event
async def on_ready():
    for guild in bot.guilds:
        if guild.name == GUILD:
            break
    
    print(
        f'{bot.user} is connected to the following guild: \n' 
        f'{guild.name} (id: {guild.id})'
    )
    
    count = 0
    for guild in bot.guilds:
        for member in guild.members:
            print(member)
            if 'Bots' not in str(member.roles):
                 
                print(member.name, ' ')
                outP.write(member.name)
                outP.write("\n")
                count += 1
    print('Number of members: ' + str(count))
票数 1
EN
查看全部 2 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65852705

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档