Discord.py on_message(),但仅用于私人消息

时间:2020-05-28 21:57:36

标签: python bots discord discord.py

所以,我正在开发一个不和谐的机器人。并且正在使用on_message()事件,该事件在私人消息和服务器上均有效。我希望这只能在私人消息中使用,并且不确定如何解决。 如果有人可以帮助我,那将是raaaaad。

import os
import discord
from discord.ext import commands


TOKEN = ''
quotedUsers = []

client = commands.Bot(command_prefix = '/')

@client.event
async def on_ready():
    print('Logged in as')
    print(client.user.name)
    print(client.user.id)
    print('------')
    await client.change_presence(activity=discord.Game(name='with myself.'))
    
@client.event
async def on_message(message):
    await message.author.send("Recieved: " + message.content)

@client.command()
async def search(ctx, *, question):
    await ctx.author.send("Searching: " + question)
    

client.run(TOKEN)```

2 个答案:

答案 0 :(得分:2)

DM组中也不存在消息行会,因此您必须检查消息传递所在的通道是否为DM。您可以使用用户的dm_channel属性:

@client.event
async def on_message(message):
    if message.channel.id == message.author.dm_channel.id: # dm only
        # do stuff here #
    elif not message.guild: # group dm only
        # do stuff here #
    else: # server text channel
        # do stuff here #

答案 1 :(得分:0)

收到DM时,它将没有公会,因此您可以像这样使用该逻辑:

@client.event
async def on_message(message):
    # you'll need this because you're also using cmd decorators
    await client.process_commands(message)
    if not message.guild:
        await message.author.send(f"Received: {message.content}")

参考: