Discord bot not recognizing messages - python-3.x

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

Related

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)

Discord.py Why removing roles doesn't work?

Giving roles work correct. But absolutely copied "on_reaction_remove" don't give any results, even exceptions. I tried to choose reactions in second account, yes, bot gave a role, but when I removed reaction bot did not do anything:/
import discord
from discord import utils
from discord.ext import commands
import config
client = commands.Bot(command_prefix = '#')
#client.event
async def on_ready():
print('Logged on as {0}!'.format(client.user.name))
#client.event
async def on_reaction_add(reaction, user):
if str(reaction.message.channel) == 'giving-roles':
try:
channel = reaction.message.channel
role = utils.get(user.guild.roles, id = config.ROLES[str(reaction)])
await user.add_roles(role)
print(f'[SUCCESS] Role [{config.ROLES[str(reaction)]} for [{user}] was added ')
except Exception as e:
print(repr(e))
#client.event
async def on_reaction_remove(reaction, user):
if str(reaction.message.channel) == 'giving-roles':
try:
channel = reaction.message.channel
role = utils.get(user.guild.roles, id = config.ROLES[str(reaction)])
await user.remove_roles(role)
print(f'[SUCCESS] Role [{config.ROLES[str(reaction)]} for [{user}] was removed ')
except Exception as e:
print(repr(e))
# RUN
client.run(config.TOKEN)
I tried this a while back and I found using on_raw_reaction_add(payload) and on_raw_reaction_remove(payload) worked better.
#client.event
async def on_raw_reaction_add(payload):
message_id = payload.message_id
#Soft Ocean
if message_id == 677963887122841625: # This can be changed but i was using an individual message
guild_id = payload.guild_id
guild = discord.utils.find(lambda g : g.id == guild_id, client.guilds) # This gets the guild
if payload.emoji.name == 'tick': #This is the name of the emoji that is used
role = discord.utils.get(guild.roles, name='Soft Ocean') # Enter the role name here
if role is not None: # If role exists
member = discord.utils.find(lambda m : m.id == payload.user_id, guild.members) #Gets the member
if member is not None: # Checks if member is real
await member.add_roles(role) # Gives the role
else:
print("Member not found")
else:
print("Role not found")
#client.event
async def on_raw_reaction_remove(payload):
message_id = payload.message_id
#Soft Ocean
if message_id == 677963887122841625:
guild_id = payload.guild_id
guild = discord.utils.find(lambda g : g.id == guild_id, client.guilds)
if payload.emoji.name == 'tick':
role = discord.utils.get(guild.roles, name='Soft Ocean')
if role is not None:
member = discord.utils.find(lambda m : m.id == payload.user_id, guild.members)
if member is not None:
await member.remove_roles(role)
else:
print("Member not found")
else:
print("Role not found")
hard worker, I certainly understand that you have already solved your problem, but I still found a way to solve it much easier than our comrades. For example see and taste this code:
#bot.event
async def on_reaction_add(reaction, member):
Channel = bot.get_channel(id ur channel)
if not member.bot:
if reaction.message.channel == Channel:
if reaction.emoji == 'ur emoji':
zxc = discord.utils.get(member.guild.roles, name="zxc")
await member.add_roles(zxc)
else:
pass
#bot.event
async def on_reaction_remove(reaction, member):
Channel = bot.get_channel(ur id )
if reaction.message.channel == Channel:
if reaction.emoji == 'ur emoji':
zxc = discord.utils.get(member.guild.roles, name="zxc")
await member.remove_roles(zxc)
Of course, brother, I understand everything (absolutely everything), the code is primitive (well, easy), but he will solve your problem like a finger on the asphalt (that is, for one or two (I hope you understand (I'm just not an Omerican))). lets giritTT

Python Discord Bot - Keep real time message parser from blocking async

I am writing a Discord Bot to take messages from a live chat and relay them to Discord channel, but want it to have other responsive features. Currently the script relays messages by entering a while loop which runs until the right message is recieved.
def chat_parser():
resp = sock.recv(4096).decode('utf-8')
#print(' - ', end='')
filtered_response = filter_fighter_announce(resp)
if resp.startswith('PING'):
# sock.send("PONG :tmi.twitch.tv\n".encode('utf-8'))
print("Ponging iirc server")
sock.send("PONG\n".encode('utf-8'))
return ''
elif (len(filtered_response) > 0):
if (filtered_response.count('ets are OPEN for') > 0):
filtered_response = get_fighters(filtered_response)
return filtered_response
return ''
fight = fight_tracker('') #initialize first fight object
def message_loop():
global first_loop_global
while True:
chat_reception = chat_parser()
if (chat_reception == ''):
continue
fight.set_variables(chat_reception)
return fight.announcement
return ''
The issue with this is that responsive functions for Discord are stuck waiting for this loop to finish. Here is the other code for reference.
#client.event
async def on_ready():
print('Finding channel...')
for guild in client.guilds:
if guild.name == GUILD:
break
channel = guild.get_channel(salty_bet_chat_id)
print('Connected to Channel.')
try:
print('Beginning main loop.')
while True:
message_out = await message_loop()
if (message_out != None and message_out != None):
print('Sending to Discord: ', message_out)
msg = await channel.send(message_out)
await msg.add_reaction(fight.fighter_1[1])
await msg.add_reaction(fight.fighter_2[1])
print('message sent...')
except KeyboardInterrupt:
print('KeyboardInterrupt')
sock.close()
exit()
#client.event
async def on_raw_reaction_add(reaction):
print(reaction)
#client.event
async def on_message(message):
print(message.author)
print(client.user)
client.run(TOKEN)
I have tried making async functions out of chat_parser() and message_loo() and awaiting their return where they are called, but the code is still blocking for the loop. I am new to both async and coding with Discord's library, so I am not sure how to make an async loop function when the only way to start the Discord client is by client.run(TOKEN), which I could not figure out how to incorporate into another event loop.

Discord.py wont respond to my if statement

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)}")

I have problem with definition of webhook

So here's the problem I don't now how to define a webhook message in if message == Here's my code:
webhook_urls = ['url1', 'url2]
#bot.event
async def on_message(message):
channels = ["global"]
if message.author.id == bot.user.id:
return
if message == DiscordWebhook:
return
for word in channels:
await message.delete()
response = DiscordWebhook(url=webhook_urls, content=message.content).execute()
It should return the webhook.
You can check if the message has a webhook_id
if message.webhook_id is not None:
...

Resources