Get message author in Discord.py - python

I am trying to make a fun bot for just me and my friends. I want to have a command that says what the authors username is, with or without the tag. I tried looking up how to do this, but none worked with the way my code is currently set up.
import discord
client = discord.Client()
#client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('$WhoAmI'):
##gets author.
await message.channel.send('You are', username)
client.run('token')
I hope this makes sense, all of the code i have seen is using the ctx or #client.command

The following works on discord.py v1.3.3
message.channel.send isn't like print, it doesn't accept multiple arguments and create a string from it. Use str.format to create one string and send that back to the channel.
import discord
client = discord.Client()
#client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('$WhoAmI'):
await message.channel.send('You are {}'.format(message.author.name))
client.run('token')

Or you can just:
import discord
from discord import commands
client = commands.Bot(case_insensitive=True, command_prefix='$')
#client.command()
async def whoAmI(ctx):
await ctx.send(f'You are {ctx.message.author}')

If you want to ping the user:
import discord
client = discord.Client()
#client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('$WhoAmI'):
await message.channel.send('You are', message.author.mention)
client.run('token')

Related

Discord Bot not responding when if statement is placed inside on_message command for event

The command "!hungry" isn't getting responded to by the bot. If I remove the if statement on line 19, the bot will respond to any message, but once I add the if statement for the specified string, I don't get any response back.
I need help on how to approach this issue. I have the code and error it gave error:
import os
import discord
from dotenv import load_dotenv
load_dotenv()
intents = discord.Intents.default()
client = discord.Client(intents=intents)
#client.event
async def on_ready():
print(f'{client.user} is now connected!')
#client.event
async def on_message(message):
if message.author == client.user:
return
** if message.content == '!hungry':
await message.channel.send('Sure. Here you go.')
await client.process_commands(message)**
client.run(os.getenv('TOKEN'))
This code without the if statement runs fine as the bot responds back to anything I type as seen below:
import os
import discord
from dotenv import load_dotenv
load_dotenv()
intents = discord.Intents.default()
client = discord.Client(intents=intents)
#client.event
async def on_ready():
print(f'{client.user} is now connected!')
#client.event
async def on_message(message):
if message.author == client.user:
return
** await message.channel.send('Sure. Here you go.')
await client.process_commands(message)
**
client.run(os.getenv('TOKEN'))
You don't have the message_content intent, so you can't read messages. Refer to the docs for more info on intents.
Also, consider just using the built-in commands framework instead of manually parsing messages.
I had the same issue.
I could make it work by toggling 'Privileged Gateway Intents' on Discord developer's page. You can find in the Bot section of your bot.
I used the below code :
(Sorry for the format I am still new to the Stack Overflow)
import discord
intent = discord.Intents.all()
client = discord.Client(intents = intent)
#client.event
async def on_ready():
print(f'We have logged in as {client.user}')
#client.event
async def on_message(message):
if message.author.name == client.user: return
if message.content.startswith('hello'):
await message.channel.send('Hello!')
client.run("token")

How to remove all reactions of a message using discord.py?

I want my bot to send a message that clears all reactions of the message after 10 seconds. How can I do that? I can't seem to find anything on the internet.
Here's my code:
import discord
from time import sleep
TOKEN = "my-discord-token"
client = discord.Client()
#client.event
async def on_message(message):
if message.author == client.user:
return
if message == "test":
msg_id = await message.channel.send("Test")
sleep(10)
{What should I put here?}
client.run(TOKEN)
Thanks!!
You should use await asyncio.sleep(10) instead of sleep(10). Discord library depends on asynchronous programming and when you use sleep(10) from the time library it freezes your entire code. This results in stoping your bot from handling other tasks properly.
You have to change if message... to if message.content. Message object contains not only the message text but other information too. You have to use message.content to get only the text part that you need.
And for clearing reactions you can use clear_reactions().
import asyncio # add this import
#client.event
async def on_message(message):
if message.author == client.user:
return
if message.content == "test": # you have to use `message.content`
msg = await message.channel.send("Test")
await asyncio.sleep(10)
await msg.clear_reactions()

Python search for string from list in string

This is what i have so far:
from discord import Embed
import os
import discord
bot=discord.Client()
nichDat=["|","~",".",",","!","pls"]
#bot.event
async def on_message(message):
if message.content != "NothingButABot":
return
for guild in bot.guilds:
print(guild.name)
for channel in guild.text_channels:
if "bot" not in channel.name:
async for message in channel.history(limit=200):
if not message.author.bot:
for dings in nichDat:
if dings not in message.content:
print(message.content)
What it should do: Print every message once that the bot can see if it isnt connected to a bot (That means none of the strings from nichDat is in it or it is not written by a bot.
What it is doing: Printing every message, that was not written by a bot 5 times.
What can i do that it is doing the right stuff?
try replacing
for dings in nichDat:
if dings not in message.content:
print(message.content)
with
if any(dings not in message.content for dings in nichDat):
print(message.content)
Your code is setup as a loop in a way that it checks each of the strings on your nichtDat list individually and if that single string is not in the message it gets printed, so your filter should not be working correctly either.
I just fixed it by making a search function and completely changing how it works.
This is how:
from discord import Embed
import os
import discord
bot=discord.Client()
nichDat=["|","~",".",",","!","pls"]
def searchfor(dings1):
for dings in nichDat:
if dings1.startswith(dings) == False:
break
print(dings1)
#bot.event
async def on_message(message):
if message.content != "NothingButABot":
return
print(message)
await bot.change_presence(activity=discord.Streaming(name='24/7 chatting', url='https://www.youtube.com/watch?v=dQw4w9WgXcQ'))
print("2")
for guild in bot.guilds:
print(guild.name)
for channel in guild.text_channels:
print(channel.name)
if "bot" not in channel.name:
print("Oke")
async for message in channel.history(limit=200):
if not message.author.bot:
searchfor(message.content)

Why isnt my discord bot answering to my messages?

I made this small discord bot to show a friend how to do it, exactly how I have done it before. But it doesnt answer my message in discord, and I cant find the error.
import discord
import os
client = discord.Client()
#client.event
async def on_ready():
print('Online as {0.user}'.format(client))
#client.event
async def in_message(message):
if message.author == client.user:
return
if message.content.startswith('Hello'):
await message.channel.send('Hello! {message.author.mention}')
client.run(os.getenv('TOKEN'))
Sorry if its obvious, I just cant see it.
Use on_message instead of in_message.
Format string 'Hello! {message.author.mention}' like f'Hello! {message.author.mention}'.
instead of using on_message events u can use
#client.command()
async def hello(ctx):
await ctx.send(f"Hello {ctx.author.mention}")
This is how u create actual Commands in discord.py

Python Bot command not working but event is

Commands not working but events are tried overriding my on_message but that didn't work. When I comment out the second client.event and down client.command works. Any idea of what I could be doing wrong? am I missing something?
import discord
from discord.ext import commands
import random
import time
from datetime import date
client = commands.Bot(command_prefix = '.')
#client = discord.Client()
#client.event
async def on_ready():
print('we have logged in as {0.user}'.format(client))
#client.command()
async def clr(ctx, amount=5):
await ctx.channel.purge(limit=amount)
#client.command(aliases =['should', 'will'])
async def _8ball(ctx):
responses =['As i see it, yes.',
'Ask again later.',
'Better not tell you now.',
"Don't count on it",
'Yes!']
await ctx.send(random.choice(responses))
#client.event()
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('hello'):
await message.channel.send('Hello how are you?')
Based on the docs (the ones mentioned by moinierer3000 in the comments) as well as other questions on stack (listed below), on_message will stop your commands from working if you do not process the commands.
#client.event()
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('hello'):
await message.channel.send('Hello how are you?')
await client.process_commands(message)
Other questions like this:
discord.py #bot.command() not running
Discord.py Commands not working because of a on_message event
Prefixed and non prefix commands are not working together on python discord bot

Categories

Resources