How to use discord bot commands and event both? - python-3.x

I need to make a bot that listen for messages written in a server, and at the same time accept commands.
# Create the Discord client
client = discord.Client()
client = commands.Bot(command_prefix = '!')
client.remove_command('help')
#client.event
async def on_ready():
print('ready')
#client.event #ricerca messaggi
async def on_message(message):
# Ignore messages made by the bot
if(message.author == client.user):
return
a = ''
a += message.embeds[0]["description"]
if a == 'abcdef':
print(' aaaaa ')
#client.command()
async def hello():
await client.say('hello')
client.run('token')
How can I make it works?
I think the problem is that the bot continue cycling in the first event...
I read about sub_process but I do not understand how to use it.

You will need to add process_commands() at the end of your on_message. This is because overriding the default on_message forbids commands from running.
#client.event #ricerca messaggi
async def on_message(message):
# Ignore messages made by the bot
if(message.author == client.user):
return
a = ''
a += message.embeds[0]["description"]
if a == 'abcdef':
await message.channel.send(' aaaaa ')
await client.process_commands(message)

instead of #client.event() just do #client.listen() and it should work and remove client = discord.Client()

Related

Discord bot bug not responding

Hello im new to stackoverflow i am developping a discord bot
but it does not react to commands in my dicsord server only in mp
here is my code
`
from discord.ext import commands
TOKEN = "X"
bot = commands.Bot(command_prefix="!")
#bot.event
async def on_ready():
print(f'{bot.user} succesfully logged in!')
#bot.event
async def on_message(message):
# Make sure the Bot doesn't respond to it's own messages
if message.author == bot.user:
return
if message.content == 'hello':
await message.channel.send(f'Hi {message.author}')
if message.content == 'bye':
await message.channel.send(f'Goodbye {message.author}')
await bot.process_commands(message)
#bot.command()
async def test(ctx, *, arg):
await ctx.send(arg)
def to_upper(argument):
return argument.upper()
#bot.command()
async def up(ctx, *, content: to_upper):
await ctx.send(content)
bot.run(TOKEN)
`
please help me
IN a server :
in a mp:
I tried a lot of thing
but nothing works i am making a nice bot for my friends and i am a noob for discord.py
ok, so, multiple #bot.event can be an issue, especially if you're looking for messages.
You need to set a listener.
I also see you do not have intents set up, so you also need to do that.
when looking for messages, you'll want something like this:
#bot.listen()#this makes the bot only listen for the messages
async def on_message(message):
# Make sure the Bot doesn't respond to it's own messages
if message.author == bot.user:
return
if message.content == 'hello':
await message.channel.send(f'Hi {message.author}')
if message.content == 'bye':
await message.channel.send(f'Goodbye {message.author}')
And just as an additional tip: use ctx.channel.send("message") instead of ctx.send("message").

My Discord Bot will not respond to any commands when I add an 'on_message'-client event

As the title suggests I'm having difficulties with my Discord Bot. I have 2 client events and a couple more commands, those are, for overview, not included in the code down below. When I comment out the 'on_message'-event all the commands function properly but as soon as I uncomment it, neither the 'on_message' nor the commands work and there is no error message in the console either so I'm clueless as to what I am doing wrong here.
client = commands.Bot(command_prefix='!', help_command=None)
#client.event
async def on_ready():
channel = client.get_channel(821133655081484318)
print(f'Welcome, {client.user.name} is up and running!')
#client.event
async def on_message(message):
with open("author.json", "r") as f:
author_dic = json.load(f)
if message.author.bot or message.content.startswith("!"):
return None
try:
for list in author_dic.values():
for el in list:
if str(message.author) == el:
channelobj = client.get_channel(list[1])
if message.channel != channelobj:
await channelobj.send(message.content)
except IndexError:
return None
#client.command()
async def getid(ctx, given_name=None):
...
client.run("TOKEN")
I'd be really glad to have someone help me out since I'm kind of lost, already thanks a lot in advance.
You have to add await client.process_commands(message) (check this issue in documentation).
#client.event
async def on_message(message):
# rest of your on_message code
await client.process_commands(message) # add this line at the end of your on_message event

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.

Get a single response from all commands

How to make bot send a specific message when users use any commands. so when user use !ping or any command it should send a default message. cozz for sometime i need to stop bot responding to all command except 1 command.
#bot.command(pass_context=True)
async def ping(ctx):
msg = "Pong {0.author.mention}".format(ctx.message)
await bot.say(msg)
You can do this in the on_message event. Example code below.
from discord.ext import commands
bot_prefix = '!'
client = commands.Bot(command_prefix=bot_prefix)
#client.event
async def on_ready():
print('client ready')
#client.command(pass_context=True)
async def ping(ctx):
msg = "Pong {0.author.mention}".format(ctx.message)
await bot.say(msg)
#client.event
async def on_message(message):
if message.startswith(bot_prefix):
await client.send_message(message.channel, 'Processing commands')
await client.process_commands(message)
client.run('TOKEN')

in discord.py how do i make it so the bot only works in one server

in discord.py, how do I make it so the bot only works on one? so is there a way do this
x = (channel id.)
if x == (12454431344645423) #this is the channel id
print ('hi')
The easiest way is to just not add it to any other servers. You can also just leave all the servers but one in your on_ready event, and then leave other servers as you join them.
import discord
client = discord.Client()
my_server = client.get_server('server id')
#client.event
async def on_ready():
for server in client.servers:
if server != my_server:
await client.leave_server(server)
#client.event
async def on_server_join(server):
if server != my_server:
await client.leave_server(server)

Resources