discord.py 客户端从服务器上踢用户

我想要的行为是,当某人的ID在列表中的时候 admins 可以让机器人踢人,使用 /kick <mention_user_to_kick> <reason>但最后却出现了错误信息

Ignoring exception in on_message
Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/discord/client.py", line 312, in _run_event
    await coro(*args, **kwargs)
  File "discordbot.py", line 325, in on_message
    await target.kick(reason=reason)
AttributeError: 'User' object has no attribute 'kick'

我找不到把用户对象转换为成员对象的方法,即使是给定的服务器公会ID(从 message.guild.id)。client.kick(user) 失败,因为 kick 的属性,而不是 client.做 client.get_user() 返回一个用户对象,所以它不起作用。message.guild.members (我所拥有的)没有任何帮助,因为它输出的是一个用户对象的迭代。

这是我目前所做的。

import discord
import asyncio
import os
import random
import time
import math


client = discord.Client()


# the list of admins is in here
with open('admins.conf', 'r') as f:
    for line in f.readlines():
        exec(line)

random.seed(os.urandom(32))
searchusers = []
bank_cooldown = {}
bans['global'] = False

@client.event
async def on_ready():
    '''Notification on ready.'''
    print('Logged in! Bot running.')
    await client.change_presence(activity=discord.Game(name='/help'))

@client.event
async def on_member_join(user):
    '''Direct message the rules on member join.'''
    await user.create_dm()
    await user.dm_channel.send(f'Hi **{user.name}**, welcome to the server! Be sure to read the rules to stay out of trouble. Have a great time!')

def isadmin(uid):
    '''Return True if user is a bot admin, False otherwise.'''
    return True if uid in admins else False

def mention_to_uid(mention):
    '''Extract the UID from a mention'''
    uid = mention[2:-1]
    if uid[0] == '!':
        uid = uid[1:]
    return uid


@client.event
async def on_message(message):

    ##########################
    # a bunch of setup stuff #
    ##########################

    if message.content.startswith('/') or message.content.startswith('&') or cmd == 2147483647:
        user = message.author.id
        name = message.author.display_name
        text = message.content[1:].strip()
        command = text.split(' ')[0]
        subcommand = text.split(' ')[1:]

        ##################
        # other commands #
        ##################

        if command == 'kick':
            if len(subcommand) < 2:
                await message.channel.send('Missing arguments! `/kick <user> <reason>`')
            if isadmin(user):
                reason = ''
                for i in subcommand[1:]:
                    reason += (' ' + i)
                reason = reason[1:]
                for member in message.guild.members:
                    if member.id == int(mention_to_uid(subcommand[0])):
                        target = member
                        break
                target = client.get_user(int(mention_to_uid(subcommand[0])))
                await target.kick(reason=reason)
                await message.channel.send('Kicked user from the server')

        ##################
        # other commands #
        ##################

client.run('Nj*********************************************************')

解决方案:

你应该做的是使用 discord.ext.commands 延长这使得这一切变得非常简单。

from discord.ext import commands
from discord import Member

bot = commands.Bot("/")

def called_by(id_list):
    def predicate(ctx):
        return ctx.author.id in id_list
    return commands.check(predicate)

@bot.command(name="kick")
@called_by(admins)
async def kick_command(ctx, target: Member, *, reason=None):
    await target.kick(reason=reason)

bot.run("token")

(当验证失败时,你可能会想添加一个错误处理程序来与用户沟通).

如果你不愿意这样做,你可以使用 Guild.get_member 而不是。

target = message.guild.get_member(mention_to_uid(subcommand[0]))

给TA打赏
共{{data.count}}人
人已打赏
未分类

JQuery文本搜索:无法获得正确的表文字搜索的tagelement。

2022-10-13 7:09:22

未分类

Blender: 渲染图像和制作动画

2022-10-13 7:20:36

0 条回复 A文章作者 M管理员
    暂无讨论,说说你的看法吧
个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索