Make a bot command - python-3.x

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')

Related

Discord.py not responding to #client.event commands

I am not getting a "ping" response with this code. It was working before, but I am not sure what changed. There are no errors on my end, just no response.
Any feedback is appreciated.
import os
import random
import discord
from dotenv import load_dotenv
from discord.ext import commands
load_dotenv()
PREFIX = os.getenv("PREFIX")
TOKEN = os.getenv("TOKEN")
intents = discord.Intents().all()
bot = commands.Bot(command_prefix=PREFIX, intents=intents)
#bot.event
async def on_message(message):
if message.author == bot.user: # tells the bot not to respond to itself
return
#bot.event # ping-with-latency
async def on_message(message):
if message.content.startswith(PREFIX + 'ping'):
await message.channel.send(f'pong! {bot.latency}ms')
#bot.event
async def on_ready(): # display if online/ready
print("Bot is ready and logged in as {0.user}!".format(bot))
# run bot on server
bot.run(TOKEN)
I have checked all permissions and privileged gateway intents. I know I could be using client.command, but that also doesnt work.
You're defining two different callbacks for these events - this is probably the problem. Just put the author check in the main on_message.
#bot.event
async def on_message(message):
if message.author == bot.user: # tells the bot not to respond to itself
return
if message.content.startswith(PREFIX + 'ping'):
await message.channel.send(f'pong! {bot.latency}ms')

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

Having some problem with discord bot which i am coding in replit

I cant start my discord bot in replti.com
Is their any fault in my code?
import os
client = discord.Client()
#client.event
async def on_ready():
print("I'm in")
print(client.user)
#client.event
async def on_message(message):
if message.author != client.user:
await message.channel.send(message.content[::-1])
my_secret = os.environ['TOKEN']
client.run(my_secret)
The method you are using is not good.
Rather do this from discord.ext import commands
and then insert commands as such:
#client.commands()
async def hello("")

Discord bot using discord.py command not working.PLZ

I just start learning how to write my own bot in discord.py. However, I followed the tutorial on Youtube, using exactly the same code but it doesn't work on my server.
import discord from discord.ext import commands
client = commands.Bot(command_prefix = '.')
#client.command(pass_context = True)
async def test(ctx):
await ctx.send('Pong!')
#client.event
async def on_ready():
print('Bot is ready')
#client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('hello'):
await message.channel.send('Hello there.')
#client.event
async def on_member_join(member):
print(f'{member}has joined the server!!')
#client.event
async def on_member_remove(member):
print(f'Seeya,{member}. Oh wait\n can we?')
client.run('NzU1MjI2Mzk1MjM5Nzc2Mjg2.XGGNZA.s2qLVQMONMLqs1f8Zky9wtM6ZDo')
Overriding the default provided on_message forbids any extra commands from running. To fix this, add a client.process_commands(message) line at the end of your on_message.
#client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('hello'):
await message.channel.send('Hello there.')
await client.process_commands(message)
Why does on_message make my commands stop working?

How to loop a task in discord.py

I am experimenting with making my own little discord bot that can get information from Twitch, but I'm stumped on how to make the bot loop and check for a condition.
I want the bot to loop a section of code every few seconds that checks if the specified twitch channel is live.
Code
import discord
from discord.ext import commands, tasks
from twitch import TwitchClient
from pprint import pformat
client = TwitchClient(client_id='<twitch token>')
bot = commands.Bot(command_prefix='$')
#bot.event
async def on_ready():
print('We have logged in as {0.user}'.format(bot))
#bot.command()
async def info(ctx, username):
response = await ctx.send("Querying twitch database...")
try:
users = client.users.translate_usernames_to_ids(username)
for user in users:
print(user.id)
userid = user.id
twitchinfo = client.users.get_by_id(userid)
status = client.streams.get_stream_by_user(userid)
if status == None:
print("Not live")
livestat = twitchinfo.display_name + "is not live"
else:
livestat = twitchinfo.display_name + " is " + status.stream_type
responsemsg = pformat(twitchinfo) + "\n" + livestat
await response.edit(content=responsemsg)
except:
await response.edit(content="Invalid username")
bot.run("<discord token>")
I want the bot to run the following code every 10 seconds, for example:
status = client.streams.get_stream_by_user(<channel id>)
if status == None:
print("Not live")
livestat = twitchinfo.display_name + "is not live"
else:
livestat = twitchinfo.display_name + " is " + status.stream_type
I've tried using #tasks.loop(seconds=10) to try and make a custom async def repeat every 10 seconds but it didn't seem to work.
Any ideas?
The newer version of discord.py doesn't support client.command()
To achieve the same I used the following snippet
import discord
from discord.ext import tasks
client = discord.Client()
#tasks.loop(seconds = 10) # repeat after every 10 seconds
async def myLoop():
# work
myLoop.start()
client.run('<your token>')
This can be done like so:
async def my_task(ctx, username):
while True:
# do something
await asyncio.sleep(10)
#client.command()
async def info(ctx, username):
client.loop.create_task(my_task(ctx, username))
References:
asyncio.create_task()
asyncio.sleep()
This is the most proper way to implement background tasks.
from discord.ext import commands, tasks
bot = commands.Bot(...)
#bot.listen()
async def on_ready():
task_loop.start() # important to start the loop
#tasks.loop(seconds=10)
async def task_loop():
... # this code will be executed every 10 seconds after the bot is ready
Check this for more info
I struggled with this as well. The problem I ran into is that none of the examples online were complete. Here is one I came up with that uses #tasks.loop(seconds=10).
import discord
import os
from discord.ext import tasks
from dotenv import load_dotenv
intents = discord.Intents.all()
client = discord.Client(command_prefix="!", intents=intents)
load_dotenv()
token = os.getenv("DISCORD_TOKEN")
CHANNEL_ID = 1234
#client.event
async def on_ready():
print(f"We have logged in as {client.user}")
myloop.start()
#client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith("hi"):
await message.channel.send("Hello!")
#tasks.loop(seconds=10)
async def myloop():
channel = client.get_channel(CHANNEL_ID)
await channel.send("Message")
client.run(token)

Resources