Discord.py wont respond to my if statement - python-3.x

I am just beginning to learn how to code with python. I tried to make a simple truth or dare game code. But the bot is not able to provess the choice and use the if statements, i cannot figure why.
Here is my code:
import discord
from discord.ext import commands
import random
bot = commands.Bot(command_prefix = "Z")
#bot.event
async def on_ready():
print("Bot is running!")
#bot.command()
async def game(ctx):
truth_items = [(list of truth questions)]
dare_items = [(list of dare questions)]
await ctx.send("please type t for truth and d for dare")
async def on_message(message):
if(message == "t"):
await ctx.send(f"{random.choice(truth_items)}")
if(message == "d"):
await ctx.send(f"{random.choice(dare_items)}")
bot.run(my_token)

To receive a reply inside a command, you should use the Client.wait_for method
#bot.command()
async def game(ctx):
truth_items = [(list of truth questions)]
dare_items = [(list of dare questions)]
await ctx.send("please type t for truth and d for dare")
def check(message):
return message.author == ctx.author and message.channel == ctx.channel and message.content.lower() in ("t", "d")
message = await bot.wait_for("message", check=check)
choice = message.content.lower()
if choice == "t":
await ctx.send(f"{random.choice(truth_items)}")
if choice == "d":
await ctx.send(f"{random.choice(dare_items)}")

Related

Make a bot command

I'm actually trying to make a bot with discord.py for me and my friends, just for fun and practice python, but, when i try to make a bot command, that can be use with prefix + [name_of_the_command], it doesn't work.
import discord
from discord.ext import commands
intents = discord.Intents(messages=True, guilds=True)
intents.message_content = True
intents.messages = True
intents.guild_messages = True
bot = commands.Bot(command_prefix="$", intents=intents)
#bot.event
async def on_ready():
print(f'Logged on as {bot.user}!')
#bot.event
async def on_message(message):
print(f'Message from {message.author}: {message.content}')
# if message.author == bot.user :
# return
# if message.channel == discord.DMChannel:
# return
#bot.command()
async def ping(ctx):
print("test")
await ctx.channel.send("pong")
bot.run('MY_BOT_TOKEN')
I search on lot's of tuto, website, forum ... to see if there is an explaination but i didn't found, so expect someone could tell me what i make wrong to this simple thing doesn't work; idk if it's change something but i'm using python 3.11.1 and the last update of discord.py (i just dl discord.py today)
That what i get in my cmd, as you can see, i have the message content, but after, that make nothing
ty and have a nice day
You have to process the command in the on_message event by using process_commands:
import discord
from discord.ext import commands
intents = discord.Intents(messages=True, guilds=True)
intents.message_content = True
intents.messages = True
intents.guild_messages = True
bot = commands.Bot(command_prefix="$", intents=intents)
#bot.event
async def on_ready():
print(f'Logged on as {bot.user}!')
#bot.event
async def on_message(message):
print(f'Message from {message.author}: {message.content}')
await bot.process_commands(message)
# if message.author == bot.user :
# return
# if message.channel == discord.DMChannel:
# return
#bot.command()
async def ping(ctx):
print("test")
await ctx.channel.send("pong")
bot.run('MY_BOT_TOKEN')

Discord bot not recognizing messages

I'm new to creating bots and I wanted to try and make a bot that would greet me when I said hi and say goodbye when I said bye.
When I activated it, it seemed to not be able to recognize that I sent a message
I checked permissions and it should be able to see it but it doesn't look like it can
here's the code
import os
import discord
client = discord.Client()
#client.event
async def on_ready():
print("We are {0.user} and we are on a cruise".format(client))
#client.event
async def on_messsage(message):
username = str(message.author).split('#')[0]
user_message = str(message.content)
channel = str(message.channel.name)
print(f'{username}: {user_message} ({channel})')
if message.author == client.user:
return
if channel == 'general':
if user_message.lower() == 'hello':
await message.channel.send(f'Hello {username}')
return
elif user_message.lower() == 'bye':
await message.channel.send(f'Bye {username}')
return
client.run(os.environ['taisho-secret'])
#client.event
async def on_message(message):
username = str(message.author).split('#')[0]
user_message = str(message.content)
channel = str(message.channel.name)
print(f'{username}: {user_message} ({channel})')
if message.author == client.user:
return
if channel == 'general':
if user_message.lower() == 'hello':
await message.channel.send(f'Hello {username}')
return
elif user_message.lower() == 'bye':
await message.channel.send(f'Bye {username}')
return
your problem is that you wrote on_messsage and its on_message

Translation with reactions not working on python

I'm trying to do a bot translation using reactions. Although something is not working.
#commands.Cog.listener()
async def on_reaction_add(self, reaction, user):
if user == self.client:
return
if reaction.emoji == ":flag_us:":
text = reaction.message.id
translate_text = google_translator.translate(text, lang_tgt='en')
await self.client.send_message(translate_text.channel)
elif reaction.emoji == ":flag_cn:":
text = reaction.message.id
translate_text = google_translator.translate(text, lang_tgt='zh')
await self.client.send_message(translate_text.channel)
else:
return
No error returned and no action made
This is because reaction.emoji isn't a string, but is an object itself. You're probably looking for reaction.emoji.name.
Also, there are a few issues within the if/elif clauses that would prevent your code from running, even if the original issue was fixed.
reaction.message.id is an integer, so passing it to google_translator.translate() will result in an error.
The name of an emoji tends not to be the name you would enter in Discord. The best practice would be to put the unicode of the emoji.
To send a message to channel, you should use TextChannel.send()
#commands.Cog.listener()
async def on_raw_reaction_add(self, payload):
if payload.member == self.client:
return
if payload.emoji.name == u"\U0001f1fa\U0001f1f8":
message = await self.client.fetch_message(payload.message_id)
translate_text = google_translator.translate(message.content, lang_tgt='en')
channel = await self.client.fetch_channel(payload.channel_id)
await channel.send(translate_text)
elif payload.emoji.name == u"\U0001F1E8\U0001F1F3":
message = await self.client.fetch_message(payload.message_id)
translate_text = google_translator.translate(message.content, lang_tgt='zh')
channel = await self.client.fetch_channel(payload.channel_id)
await channel.send(translate_text)
This would work, but I would recommend taking all of the various calls outside of the if/elif clauses:
#commands.Cog.listener()
async def on_raw_reaction_add(self, payload):
if payload.member == self.client:
return
emoji_to_language = {
u"\U0001f1fa\U0001f1f8": "en",
u"\U0001F1E8\U0001F1F3": "zh"
}
lang = emoji_to_language.get(payload.emoji.name)
if lang is None:
break
message = await self.client.fetch_message(payload.message_id)
translate_text = google_translator.translate(message.content, lang_tgt=lang')
channel = await self.client.fetch_channel(payload.channel_id)
await channel.send(translate_text)

Why does my on_message event doesn't work (discord.py)

I'm making a discord bot that worked fine but I wanted to start using cogs because I thought it was a nicer way to write my code but now my on_message doesn't work any more and it doesn't show any error messages I searched how to fix it in the whole internet and all explanations didn't work for me so I decided to ask here. So here is my code:
from discord.ext import commands
TOKEN = 'my token'
bot = commands.Bot(command_prefix="$")
class Interactions(commands.Cog):
#commands.Cog.listener()
async def on_message(self, message):
msg = message.content
hi = ["hi", "hello", "hi!", "hello!"]
bye = ["bye", "good bye", "bye!", "good bye!"]
# Messages in english
if str(msg).lower() in hi:
await message.channel.send('Hello!')
if str(msg).lower == 'how are you?':
await message.channel.send("I'm fine")
if str(msg).lower == "what's your favorite food?":
await message.channel.send("Sushi with sweet potato!")
if str(msg).lower == "what do you eat?":
await message.channel.send(
"I don't eat, I'm just a simple bot :pensive:")
if str(msg).lower == "are you fine?":
await message.channel.send("Yes, I am")
if str(msg).lower in bye:
await message.channel.send("Good bye!")
def run():
bot.add_cog(Interactions(bot)
bot.run(TOKEN)
if __name__ == "__main__":
run()
Import:
from discord.ext.commands import command, Cog
Rest of the code:
TOKEN = 'my token'
bot = commands.Bot(command_prefix="$")
class Interactions(commands.Cog):
#commands.Cog.listener()
async def on_message(self, message):
pass
This should work, if not just ping me ;)

How do I get the discord bot to trigger commands on it's own message using discord.py?

Let's just say the user enters an invalid command, the bot suggests a command with (y/n)? If y, then the bot should trigger the suggested command.
I feel this can be achieved in 2 ways:
If the bot can trigger commands on its own message
If I can call the command from the other cogs
I can't seem to get either of em working.
Here is an example to help you guys help me better:
Let's just say this below code is from a cog called Joke.py:
#commands.command()
async def joke(self,ctx):
await ctx.send("A Joke")
And then there another cog "CommandsCorrection.py" that corrects wrong commands used by the user that are saved on data.json file:
#commands.Cog.listener()
async def on_message(self, message):
channel = message.channel
prefix = get_prefix(self,message)
if message.author.id == bot.id:
return
elif message.content.startswith(prefix):
withoutprefix = message.content.replace(prefix,"")
if withoutprefix in data:
return
else:
try:
rightCommand= get_close_matches(withoutprefix, data.keys())[0]
await message.channel.send(f"Did you mean {prefix}%s instead? Enter Y if yes, or N if no:" %rightCommand)
def check(m):
return m.content == "Y" or "N" and m.channel == channel
msg = await self.client.wait_for('message', check=check, timeout = 10.0)
msg.content = msg.content.lower()
if msg.content == "y":
await channel.send(f'{prefix}{rightCommand}')
elif msg.content == "n":
await channel.send('You said no.')
except asyncio.TimeoutError:
await channel.send('Timed Out')
except IndexError as error:
await channel.send("Command Not Found. Try !help for the list of commands and use '!' as prefix.")
in the above code await message.channel.send(f"Did you mean {prefix}%s instead? Enter Y if yes, or N if no:" %rightCommand) suggests the right command and await channel.send(f'{prefix}{rightCommand}') sends the right command.
So,for example:
user : !jok
bot : Did you mean !joke instead? Enter Y if yes, or N if no:
user : y
bot : !joke **I want to trigger the command when it sends this message by reading its own message or my just calling that command/function
How should I go about this?
One solution would be to separate the logic of your commands from the command callbacks and put it in it's own coroutines. Then you can call these coroutines freely from any of the command callbacks.
So you would turn code like this:
#bot.command()
async def my_command(ctx):
await ctx.send("Running command")
#bot.command()
async def other_command(ctx, arg):
if arg == "command":
await ctx.send("Running command")
Into something like this:
async def command_logic(ctx):
await ctx.send("Running command")
#bot.command()
async def my_command(ctx):
await command_logic(ctx)
#bot.command()
async def other_command(ctx, arg):
if arg == "command":
await command_logic(ctx)
#Patrick Haugh suggested this idea, he was on to something but wasn't really working but I got a way to get it working.
If you use the following method for a cog, you'll be able to read bot commands as well:
import discord
from discord.ext import commands
async def command_logic(self, ctx):
await ctx.send("Running command")
class Example(commands.Cog):
def __init__(self, client):
self.client = client
#commands.command()
async def my_command(self, ctx):
await command_logic(self,ctx)
#commands.Cog.listener()
async def on_message(self, message):
if message.content == '!command':
ctx = await self.client.get_context(message)
await command_logic(self,ctx)
def setup(client):
client.add_cog(Example(client))

Resources