Discord.py automatic message handler - discord.py

this code (discord.py's Cog) should simply send a "Hello World" message.What im trying to do is a exercise. It would be also useful to know how to make it work on a loop(eg. every 2hrs). What im trying to achive, is that, when the bot has started, it will automatic send Hello World in channel (ID). anyone know how i can solve this?
I tried using an event listener, with different guides from discord.py repository but nothing seems to be working.
import discord
from discord.ext import commands
from discord.ext.commands import Context
from helpers import checks
class Tickets2(commands.Cog, name="ticket2"):
def __init__(self, bot):
self.bot = bot
#commands.hybrid_command(
name="ticket2",
description="Hello Wolrd."
)
#checks.not_blacklisted()
async def ticket2(self, context: Context) -> None:
"""
Stampa a video hello
"""
channel = self.bot.get_channel(1066374083803107518)
await channel.reply('hello')
async def setup(bot):
await bot.add_cog(Tickets2(bot))

Related

Cogs Not Working and not detected In Discord.py

My bot program can't detected cogs file
I have tried every way to solve it, but still nothing has changed
main.py
import discord
import os
from discord.ext import commands
intents = discord.Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix='$', intents=intents)
async def load():
for filename in os.listdir('./cogs'):
if filename.endswith('.py'):
await bot.load_extension(f'cogs.{filename[:-3]}')
bot.run('MTA2NzQ1MDMxMTAzMzIzMzUxOA.GSdg-i.CW3X5T82VYGYjPqEPWZ8YQ6oDZni33T-Bi1Ovo')
lab.py
import discord
from discord.ext import commands
class lab(commands.Cog):
def __init__(self,bot):
self.bot = bot
#commands.Cog.listener()
async def on_ready(self):
print('lab.py is running')
#commands.command()
async def holla(ctx):
await ctx.reply('hai')
async def setup(bot):
await bot.add_cog(lab(bot))
eror
I need someone to help me solve my problem, thanks in advance
You're never calling that load() function... It's cool that you made it, but if you're not using it then it's not very surprising that your cogs aren't being loaded.
The recommended place to do this in is setup_hook. Subclass Client (or Bot depending on what you want) and override it.

Can't figure out how to use discord.py ctx

I have tried to convert my discord bot's commands to using ctx instead of interactions but the code I have tried below does not work.
#bot.command(description="Says test")
async def test(ctx):
await ctx.send("Test")
My issue is that the command never loads.
Updated code but still broken
import discord
from discord import ui
from discord.ext import commands
bot = commands.Bot(command_prefix="/", intents = discord.Intents.all())
# Run code
#bot.event
async def on_ready():
print('The bot has sucuessfully logged in: {0.user}'.format(bot))
await bot.change_presence(activity=discord.Activity(type = discord.ActivityType.listening, name = f"Chilling Music - {len(bot.guilds)}"))
# Commands
#bot.command(description="Says Hello")
async def hello(ctx):
await ctx.send(f"Hello {ctx.author.mention}!")
#bot.command(description="Plays music")
async def play(ctx, song_name : str):
await ctx.author.voice.channel.connect()
await ctx.send(f"Now playing: {song_name}")
#bot.command(description="The amount of servers the bot is in")
async def servercount(ctx):
await ctx.send(f"Chill Bot is in {len(bot.guilds)} discord servers!")
#bot.command(description="The bots ping")
async def ping(ctx):
await ctx.send(f"🏓Pong\nChill Bot's ping is\n{round(bot.latency * 1000)} ms")
#bot.command(description="Announcement command")
async def announce(ctx, message : str):
await ctx.send(message)
#bot.command(description="Support Invite")
async def support(ctx):
await ctx.send(f"{ctx.author.mention} Please join our server for support! [invite]", ephemeral=True)
#bot.command(description = "Syncs up commands")
async def sync(ctx):
await ctx.send("Synced commands!", ephemeral=True)
bot.run('')
Your commands don't work because you incorrectly created an on_message event handler.
By overwriting it and not calling Bot.process_commands(), the library no longer tries to parse incoming messages into commands.
The docs also show this in the Frequently Asked Questions (https://discordpy.readthedocs.io/en/stable/faq.html#why-does-on-message-make-my-commands-stop-working)
Overriding the default provided on_message forbids any extra commands from running. To fix this, add a bot.process_commands(message) line at the end of your on_message.
Also, don't auto-sync (you're doing it in on_ready). Make a message command and call it manually whenever you want to sync.

Discord.py bot not able to send embed messages?

Trying to implement embedded messages for my discord bot using interactions. The following is the code with the error message under it.
import interactions
import discord
bot = interactions.Client(token="<REDACTED>")
#bot.command(
name="test",
description="Tests"
)
async def test(ctx: interactions.CommandContext):
embed = interactions.Embed(
title="testing",
description="test purposes"
)
await ctx.send(embed = embed)
Error Message:
payload = await super().send(content, **kwargs)
TypeError: _Context.send() got an unexpected keyword argument 'embed'
interactions.py documentation said This is quite simple: The argument embed got deprecated by Discord. The new naming is embeds.
Changed embed into embeds and it works now.
#bot.command(
name="test",
description="Tests"
)
async def test(ctx: interactions.CommandContext):
embeds = interactions.Embed(
title="testing",
description="test purposes"
)
await ctx.send(embeds = embeds)

Sending a message through discord.py after message edit check

I have a function that checks if 'your' is changed to 'you're' and I am having trouble having the bot send a message after this check. What is the proper way to do this? (I want this to apply to all channels.)
import discord
from discord.ext import commands
client = discord.Client()
bot = commands.Bot(command_prefix='$')
#client.event
async def on_ready():
print("We have logged in as {0.user}".format(client))
#client.event
async def on_message_edit(before,after):
if(before.content == "your" and after.content == "you're"):
# I want to send message here
client.run('Token') # I have my token here
Add ctx into the parameters (before,after,ctx), and
then put in await ctx.send("message") where you want your message to send.
the parameters before and after are of type discord.Message. discord.Message has an attribute channel, with which you can use the function send.
#client.event
async def on_message_edit(before, after):
if before.content == 'your' and after.content == "you're":
await before.channel.send(send_whatever_you_want)

discord bot python auto-role(help)

import discord
from discord.ext import commands
print(discord.__version__)
client = commands.Bot(command_prefix = '!')
#client.event
async def on_ready():
print('bot is online')
#client.event
async def on_member_join(member):
role = get(member.guild.roles, name="Members")
await member.add_roles(role)
print(f"{member} was given {role}")
client.run(removed)
what am I doing wrong here? I am trying to make an auto-join role when somebody joins it gives him a role
In version 1.5 intents were introduced which directly effect events like on__member_join. You would need to enable it in the Discord Developer Portal under bot in your application. Once that is enabled you would want to add this:
intents = discord.Intents.default()
intents.members = True

Resources