Discord.py Rewrite: Functions suddenly stopped working - python-3.x

I've been messing around with the discord bot python rewrite for the last few days. I've noticed that adding multiple functions tends to cause other functions to stop working. I added a looping task that sends a video from a random list of URLs and I initially thought that may be causing the other functions to stop working, but commenting that out still causes issues. It's pretty annoying when you have no error messages to go off of. Any help would be greatly appreciated!
import discord
from discord.ext import commands, tasks
import re
from random import randint
client = commands.Bot(command_prefix = "//")
#client.event
async def on_ready():
print("The bot is doing stuff.")
#client.event
async def on_message(message):
"""Deletes <specific> YT link"""
if <specific yt link> in message.content:
await message.delete()
print("video deleted")
#client.event
async def on_message(message):
"Sends a peeposalute whenever someone says 'goodnight'"
gn = re.compile('goodnight|good night|gn')
if gn.search(message.content.lower()):
await message.channel.send('<:peepoSalute:665687773407215637>')
print('peepo has saluted')
#client.event
async def on_message(message):
"""Checks the #new-uploads channel, reacts to any new messages and adds the video URL to the list"""
if message.channel.id == <channel id>:
with open('videos.txt', 'a') as f:
f.write(message.content + '\n')
print("New video added to list")
message.add_reaction('<:Wowee:592122719546638408>')
#tasks.loop(hours=24)
async def daily_video():
"""Sends a random video in #general daily"""
with open('videos.txt', 'r') as f:
videos = f.readlines()
target_general_id = <channel id>
general_id = client.get_channel(target_general_id)
await general_id.send(videos[randint(0, len(videos) - 1)])
print("Daily video sent")
#daily_video.before_loop
async def before():
await client.wait_until_ready()
print("Finished waiting")
daily_video.start()
client.run(<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')

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

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

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)

How should I Private DM my user after they send a command? (Discord Python)

I am coding a python discord program, and I'm very new to this. I tried a few answers to Private DMs, but none of them seemed to work. I can't tell if I am doing anything wrong. I would like any user/a user with a role to say a command, eg .gen and the bot sends dm.
My code:
import discord
import random
from discord.ext import commands
from random import randint
bot = commands.Bot(command_prefix='.', description='Generates accounts')
x=1
spotifynum = 0
spotifyvisnum = 1
with open("spotify.txt") as f:
spot = f.readlines()
spot = [x.strip() for x in spot]
with open("spotify.txt") as f:
spot = f.readlines()
spot = [x.strip() for x in spot]
#bot.event
async def on_ready():
print(("-")*40)
print('Logged in as')
print(bot.user.name)
print(("-")*40)
#bot.command()
async def hello():
await bot.say('Hello!')
#bot.command()
async def gen():
await ctx.author.send("hi")
bot.run('private_code')
You are looking at the docs for rewrite, but probably using async code. You need to use await bot.send(dest, message) to send messages in async

Resources