【问题标题】:discord.py client kick user from serverdiscord.py 客户端从服务器踢出用户
【发布时间】:2020-05-08 06:27:44
【问题描述】:

我的预期行为是当 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*********************************************************')

【问题讨论】:

  • 这能回答你的问题吗? How to kick users on command
  • @DerteTrdelnik 我不能踢discord.User 对象,它必须是成员对象
  • 你试过message.guild.kick(user)吗?

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


【解决方案1】:

你应该做的是使用discord.ext.commands extension,这让这一切变得非常简单:

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]))

【讨论】:

    猜你喜欢
    • 2013-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-28
    • 2018-04-13
    • 2016-07-06
    • 2012-04-26
    • 2013-02-23
    相关资源
    最近更新 更多