I need bot which can detect the user's role in Direct Message. I was able to do it from the server chat, but i need it to be done in direct messages too. My current code simplified:
import discord
client = discord.Client()
@client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
role1 = 'ROLE_ID'
@client.event
async def on_message(message):
#only user with role1 is able to send the command
if message.content.lower().startswith('can I?'):
for r in message.author.roles:
if str(r.id) in role1:
await message.channel.send('Yes you can!')
return
#everyone is able to send the command $hello
if message.content.startswith('Hello'):
await message.channel.send('Hi!')
client.run('TOKEN')```
Do not confuse a Member
object with a User
object. User
has no role, as it is not related to a server as a Member
. What you can do is get that user's member to the desired server:
import discord
client = discord.Client()
@client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
role1_id = 000000000000000000000
guild1_id = 000000000000000000000
@client.event
async def on_message(message):
if message.content.lower().startswith('can I?'):
if message.guild:
member = ctx.author
else: # private message
guild = client.get_guild(guild1_id)
member = await guild.fetch_member(ctx.author.id)
# only user with role1 is able to send the command
for r in member.roles:
if r.id == role1_id:
await message.channel.send('Yes you can!')
return
#everyone is able to send the command $hello
if message.content.startswith('Hello'):
await message.channel.send('Hi!')
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.