2017-05-14 107 views
2

我试图用discord.py编写一个简单的机器人提一个用户,所以我开始与乐趣命令,如刚刚拿到API的窍门我如何使用用户ID在discord.py

import discord 
import asyncio 
client = discord.Client() 


@client.event 
async def on_message(message): 
    # we do not want the bot to reply to itself 
    if message.author == client.user: 
     return 

    if message.content.startswith('!hug'): 
     await client.send_message(message.channel, "hugs {0.author.mention}".format(message)) 

    # Greetings 
    if message.content.startswith('hello'): 
     msg = 'Hello {0.author.mention}'.format(message) 
     await client.send_message(message.channel, msg)   

    # say (id) is the best 
    # This is where I am lost. how to mention someone's name or id ? 
    if message.content.startswith('!best'): 
     mid = User.id('ZERO#6885').format(message) 
     await client.send_message(message.channel, '{mid} mentioned') 
+1

'discord.py'从哪里来? – boardrider

回答

5

所以,我终于想通了如何做到这一点后,试验和错误,希望其他的几天会从中受益,并具有痛苦少,比我其实是有.. 的解决方案是最终容易..

if message.content.startswith('!best'): 
     myid = '<@201909896357216256>' 
     await client.send_message(message.channel, ' : %s is the best ' % myid) 
1

User对象中,使用属性User.mention来获取表示为用户提及的字符串。要从其ID中获取用户对象,您需要Client.get_user_info(id)。要从用户名('ZERO')和鉴别符('#6885')中获取用户,请使用效用函数discord.utils.get(iterable, **attrs)。在上下文:

if message.content.startswith('!best'): 
    user = discord.utils.get(message.server.members, name = 'ZERO', discriminator = 6885) 
    # user = client.get_user_info(id) is used to get User from ID, but OP doesn't need that 
    await client.send_message(message.channel, user.mention + ' mentioned') 
+0

文件“\ client.py”,第307行,来自getattr(self,event)(* args,** kwargs)的_run_event yield 文件“bot.py”,第39行,on_message id = User.id 'ZERO#6885')。格式(消息)#或任何你正在做的事情得到ID NameError:名称'用户'没有定义 –

+0

好吧,你的方法得到身份证不起作用 - 对不起,我didn没那么清楚。我会用一种可以工作的方法进行编辑 –

+0

@ItachiSama在进一步阅读之后,你实际上没有用户的ID:你有他们的用户名和鉴别符。我已经更改了代码以反映这一点,并且如果您在评论中有ID,则可以使用该方法。 –

1

如果你在命令工作,你最好使用discord.py内置的命令功能,你的拥抱命令将变为:

import discord 
from discord.ext import commands 

@commands.command(pass_context=True) 
async def hug(self, ctx): 
    await self.bot.say("hugs {}".format(ctx.message.author.mention())) 

这是地设想你在你的代码开头做了这样的事情:

def __init__(self): 
    self.bot = discord.Client(#blah)