#discord-bots
1 messages · Page 336 of 1
given that is_premium only really needs the bot, i suggest turning it into a regular function and accessing bot from the interaction with interaction.client
e.g. ```py
async def premium_cooldown(interaction: discord.Interaction) -> app_commands.Cooldown:
bot = interaction.client
...
in your cog:
@app_commands.command()
@app_commands.checks.dynamic_cooldown(premium_cooldown)```
Thanks but caninteraction.client access my database that I made with using SQLITE?
interaction.client is whatever bot instance is receiving the interaction, and i'd assume you only have one bot instance that you've been using across your code
So i have a file called cog_setup1.py inside of a folder called commands, which does all cogs n stuff, the in my Bot.py file i just load the cog_setup1. How could I restart the cogs? I have tried restarting it before, but then it says my cogs are already loaded. I am wondering how I can do that?
If that doesn't explain it well, here is what I mean, this Ticket system I made kinda explains what I mean.
Discord Ticket System made in Discord.py. Contribute to RejectModderss/TicketSystem development by creating an account on GitHub.
!d discord.ext.commands.Bot.reload_extension should work just fine for your layout
await reload_extension(name, *, package=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Atomically reloads an extension.
This replaces the extension with the same extension, only refreshed. This is equivalent to a [`unload_extension()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.unload_extension) followed by a [`load_extension()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.load_extension) except done in an atomic way. That is, if an operation fails mid-reload then the bot will roll-back to the prior working state.
This should go into Bot.py correct?
oh wait, not sure if discord.py can tell where the cogs came from...
doesn't have to be bot.py, you can call that function wherever you want
When I do this
Its saying the cogs are already loaded.
meaning it didn't unload them clearly when its supposed to
hmm yeah, it needs to be reorganized as an actual package
see https://docs.python.org/3/tutorial/modules.html#packages, but basically rename cog_setup1.py to __init__.py and then in (re)load_extension, import the package as "commands" rather than "commands.cog_setup1"
you can also check the source code for more details, but essentially it only recognizes cogs to unload if either:
- your extension is a module (a .py file) and the cogs are defined inside that module;
- your extension is a package (
__init__.py) and the cog is defined in init or a submodule
discord/ext/commands/bot.py lines 885 to 890
async def _remove_module_references(self, name: str) -> None:
# find all references to the module
# remove the cogs registered from the module
for cogname, cog in self.__cogs.copy().items():
if _is_submodule(name, cog.__module__):
await self.remove_cog(cogname)```
how to get the day that the bot joined the server.
It worked, but that was such a simple fix man
you are a legend
Everyone else would say like, use reload kinda like you said, even tho I showed them what I was talking about, because that wasn't gonna work, then they would say yes it would. But it clearly didn't but you are like the only one who sat there n explained it
if you have the guild object, get your bot's own member object and then check the joined_at date
nextcord.Guild.me -> nextcord.Member.joined_at
Hello! Is it possible to embed/attach an image to discord thread post via api? Couldn't find it in the documentation for discord.py
its similar to sending attachments in regular messages, create a discord.File object (using either a filename or a file-like object) and pass it to the create_thread(file=) parameter
Thank you! I'll look into it right away
i need to send messages to multiple channels, i've tried looping over an array of channel id's but it will only send a message to the last object in the list
@tasks.loop(seconds=3)
async def sendMessage():
try:
with open('utils/config/channels.json', 'r') as f:
channels = json.load(f)
for channel in channels:
c = durere.get_channel(channel)
await c.send('test')
print(channel)
print(f'sent message to: {c.name}')
except Exception as e:
print(e)
[
1186639720397656805,
1186719615569941656
]
icationError: (1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1006)')]
what does this mean?
MacOS? Navigate to your Applications/Python 3.X/ folder and double click the Install Certificates.command to fix this.
Nah windows
are you using discord.py 2.0? if so, the add_cog() method has to be awaited
https://discordpy.readthedocs.io/en/stable/migrating.html#extension-and-cog-loading-unloading-is-now-asynchronous
there is some kind of bots that you can insert an bot token in it then the bot that you inserted its token will work in a certin project or code
does anyone has an idea how this thing work?
they're just like normal bots. the code is already there, all it needs is a token
robin
what programming abilities does one have who has made an insane amount of discord bots
I dunno what to write in my resume
I just have
Python:
oop
asyncio
APIs
1 bot can run more than 1000 bots just by inserting a token
also, can you give example pls?
this is a better question for #career-advice
maybe
that's not possible, unless you have 1000 tokens
one token = one bot
can you give example for how that works ?
?
I think you didnot understand me
the that I talking about its called 'bot maker' you just select the bot will work in wich code then in a modal just insert the token and the prefix and the bot will work immeditly
how is this different from any normal bot
it's like, basically the same as @novel apex . just put in your token and it works
you put it in the project then run it
not in modal and chose the prefix also in modal
well at a very superficial level you would create another bot instance and spawn it in a thread using asyncio and the current bot event loop
bots have had per-server custom prefixes for ages. it's nothing new
How can i make slash commands in replit?
im trying to make a command so basically you run a command and put a number, that number goes into a list with the server id so that it saves, but im having 2 different problems, #1 is that every time that a server runs the command multiple times it will give adding on to the list but i wanna make it where if the same server runs it multiple times then instead of keep adding on to the list it just updates and whatever number they put will change. and my other problem is i have a command to check the number to make sure that everytime the bot turns off the number saves but every single time that the bot restarts and i check, it just says 0 but it does stay in the list.
So basically, the number does store into the json file but if i do it twice then it adds on twice which i dont want and when i run the get command it will tell me the number right if i dont restart the bot but if i restart the bot and try it itll say 0.
i fixed the part where it added twice, but when i run the command if i restart the bot it still gives me 0
save_RC should probably be unindented so that it saves regardless of if it was updated or set
is there a way to only have your bot listen to whitelisted users?
@client.tree.command(description='rostercap')
async def set_roster_cap(ctx, cap: int):
if ctx.guild:
server_id = ctx.guild.id
if server_id in RC:
RC[ctx.guild.id] = cap
await ctx.response.send_message(f"Roster cap updated to {cap}")
else:
RC[server_id] = cap
await ctx.response.send_message(f"Roster cap set to {cap}")
save_RC()```
like this? I did but even then it still gives me 0
it goes into the list but when i run the get command it just says 0 idk why
does the json file get updated properly?
try
RC.get(str(ctx.guild.id), 0)
in the get function
wait 1 question, so I kinda fixed it but not fully apparantly, so basically if i run the command multiple times and keep switching it wont add onto the list it just updates. BUT if i set a number and then restart the bot and then set a number again on the same server THEN it adds onto the list twice, how do I make it where reagrdless if i restart the bot or not it doesn't add the same server twice and it just updates
TypeError: BotBase.__init__() missing 1 required keyword-only argument: 'intents'
import discord
from discord.ext import commands
client = commands.Bot(command_prefix = '.')
@client.event
async def on_ready():
print("Sharp is ready.")
print("-----------------------")
@client.command()
async def hello(ctx):
await ctx.send("hello boss.")
someone please tell me
what im doing wrong 😭
when you declare client, you aren't declaring what intents you need. the commands.bot requires it. Here is how it traditionally looks:
bot = commands.Bot(command_prefix="!", intents=discord.Intents.all())
is there an easy way to make your bot user whitelist only?
or is it a fair amount of lines to code
thank you for the reply, watching a video and it must be outdated.
just try "rank_level"?
You want to see the code ?
um just send me a screenshot of the directory where your file sits
yeah
but I got a problem, when I execute the program
it put the DB on python
so maybe that's why
python is the sub directory
Okay it was that but now idk how to execute it in the bot_discord directory can someone help ?
Yeah it's pretty easy
!d discord.ext.commands.Bot.check
@check```
A decorator that adds a global check to the bot.
A global check is similar to a [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check) that is applied on a per command basis except it is run before any command checks have been verified and applies to every command the bot has.
Note
This function can either be a regular function or a coroutine.
Similar to a command [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check), this takes a single parameter of type [`Context`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Context) and can only raise exceptions inherited from [`CommandError`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CommandError).
Example...
where would i add this?
im not familiar with python or discord.py so im not really sure what to do..
Anywhere
welcome to the club
im trying to make a command where when i put a server id it puts it in a list, but it dont work, what am i doing wrong?
async def whitelist(ctx, server_id: int):
if server_id not in f.whitelistedservers:
f.whitelistedservers.append(server_id)
print(f'Added {server_id} to whitelistedservers: {f}')
await ctx.response.send_message(f'{server_id} has been whitelisted.')
else:
await ctx.response.send_message(f'{server_id} is already in the whitelist.')```
What is it showing? @somber sky
theres no error it just doesnt go into the list
Looks fine to me
Did you run command again with same id after adding it?
yes
You won't see changes in code
the reason that id is there is because i made it where if your server id isnt inside of the list then it will just leave the server because it has to be whitelisted, so the reason that id is there is so it doesnt leave my testing server
i just want it to add on to the list but if i take out the server id i already have then i cant even test it cause it wont be able to join my server
Okay, but you're showing the code and saying it's not changing
It'll be changed in memory, so you'll need to print it to see the changes take effect
wdym
Hey for some reason when I'm syncing my commands after loading my cogs, it doesn't sync but registers into other servers that the bot is in.
@bot.tree.command(name="sync", description="sync a command", guild=discord.Object(id=1197312375301345280))
@app_commands.checks.has_role('*')
async def sync(interaction: discord.Interaction):
await interaction.response.send_message("commands should be synced", ephemeral=True)
await bot.tree.sync()
await bot.tree.sync(guild=discord.Object(1197312375301345280))
await interaction.response.send_message("commands should be synced", ephemeral=True)
so then how do i make it where it puts the id in the list
are discord bots a good way to improve my python knowledge(im somewhere between beginner and intermediate), would it be helpful if i wanna continue down the path as a software engineer?
if you implement complex and interesting features, sure. Coding a bot itself isn't though. Not really lol
The discord.py library is really nice and easy/comprehensive, so it's easy to grasp and learn
but creating complex features that require working around the niches and caveats of an asyncio app is a decent learning curve (ish)
since idk about bots ig i'll start with something easier then try making more complex bots, thanks for the answer
Hey member.add_role(userID, roleID) works right ?
because idk why when the bot try to asign the role it tells me the role is not existing
that's not how it works
you need to pass in an actual role object, and the method is called add_roles
member = guild.get_member(1234)
role = guild.get_role(1234)
# Check if any of those are None or something...?
await member.add_roles(role)
1234 is the name of the role ?
it will only work for one server then ?
async def level_role(member, lvl):
with open("rank_level.txt", "r") as f:
if lvl == 5:
role = f.readlines(1)
await member.add_roles(role)
if lvl % 10 == 0:
role = f.readlines(int((lvl / 10) + 1))
await member.add_roles(role)
So my .txt with all my ID is useless ?
replace 1234 with your role id
oka
he said make a variable
role = guild.get_role(1234)
before doing
await member.add_roles(role)
or replace
await member.add_roles(role)
with
await member.add_roles(guild.get_role(role))
that will work
not really clean but should work
technically add_roles() can accept a generic discord.Object, so you really only need the member object and the ID: py await member.add_roles(discord.Object(1234))
oh nice that's what someone told me
i'll check it tomorrow am tired
.get_guild(id) / fetch_guild
Tho i recommend get guild
Also you dont want to use a .txt for this stuff. Just generally considered bad practice
then how do I storage my things ?
Faced recently an issue, bot works create but after a time gets timeout and stop working, created new token worked and same issue happened again.
disnake.ext.commands.errors.CommandInvokeError: Command raised an exception: NotFound: 404 Not Found (error code: 10062): Unknown interaction
For this code part:
@channel.sub_command()
async def buttons(inter, channel: disnake.TextChannel):
if inter.author.bot:
return
await inter.response.defer(with_message=True, ephemeral=True)
view = disnake.ui.View()
The problem was- when the bot got into having this problem - scraping most of the code, and just had the: "await inter.response.defer(with_message=True, ephemeral=True)" and an output in the bot log, nothing happend and it timed out even by that .
creating a whole new bot - cloning the code project, and it was working again. until bot was invited to server a few days later and having it run for a couple of hours first time, the problem occured again and restart of the bot didn't fix it. only creating a new bot worked.
where do I put that BTW ?
.json, .db, sql, mongo
thats just to get the guild objet to get the roles
so bot.get_guild(guild_id)
you should use bot
discord.ext.bot is a subclass of client but with more featuers
why ? I made everything with client
youre not reading what im saying
its a subclass, so it has everything, except its a generally improved and more extensive version of Client
I am reading just wrote it as the time you sent the message xD
okay so i'll recode everything...
but I have to put bot = discord.bot(intents=intents) in every file I make ?
no
Just put that after you call your command_prefix, so after that just do , intents=intents, then set intents to all.
intents = discord.Intents.all()
bot = commands.Bot(command_prefix='!', intents=intents)
Hey! I'm losing my mind over 2 things:
-
Forum Topic Tags are not working on my new version of the code.
-
embedded url for topic image only works when manually setting it. Bot will not grab the right thing from api.
I have attached a link for both codes with a sample api response as well.
https://paste.pythondiscord.com/ORUQ
https://paste.pythondiscord.com/AYKQ
In an ideal world the script would add tags correctly from the database and also embedd and image for the post
the tag IDs in the second file seem invalid, but what happened to calling the built-in ForumChannel.create_thread() method?
I modified the tag id's to protect myself before posting here. About the built-in method for creating a forum post i have to blame gpt as that's all i have currently access to
I would love to not do this myself but as a startup it's tight right now
I don't want a command prefix I only want to make /commands
then how do I get bot or client on the second file ?
u need to use cogs
Ok I'll check about it I have a video in a playlist I watch about making bot
yeah u can just make sure u dont define prefix commands thats it
most videos are pretty outdated so i would be careful about that
IDs don't grant any permissions and only convey the timestamp of when they were created so i wouldn't worry about that, but regardless the payload itself seems to be almost correct as per the discord api docs
only thing that shouldn't be there is the type value because all "threads" in forum channels are public
Do you have good source for cogs ?
A hands-on guide to Discord.py
u would also need to load the cogs for which u can check cogs page oh how that works
as a sidenote, requests is a blocking library and will momentarily interrupt your bot while it waits for responses so if you're doing frequent requests, httpx or aiohttp would be more optimal: ```py
import aiohttp
async def make_request():
async with aiohttp.ClientSession() as session:
async with session.get(url, params=..., headers=...) as response:
data = await response.json()
...``` (aiohttp is what discord.py already uses)
thank you, this is good to know! Right now it makes requests once per day. However do you have a clue on how to extract the first url for embedding the image via api. As that's what im struggling with currently. Aside from me breaking the tag functionality
shrug, your image_data[0]['url'] seems to match the json snippet
oh, if not row['field_4804']: would be false though
Ahh I see, here's how I do my commands
import discord
from discord import app_commands
guild_id = 1234
class aclient(discord.Client):
def __init__(self):
super().__init__(intents = discord.Intents.all())
self.synced = False
async def on_ready(self):
await self.wait_until_ready()
if not self.synced:
await tree.sync(guild = discord.Object(id=guild_id))
self.synced = True
client = aclient()
tree = app_commands.CommandTree(client)
@tree.command(guild = discord.Object(id=guild_id), name = 'test', description='...')
async def test(interaction: discord.Interaction):
await interaction.response.send_message(f"test", ephemeral = True)
client.run('token')
can you send it in DM ?
commands.Bot still offers the cogs/extensions system which interoperates with slash commands fairly well, it's just somewhat annoying that dpy still requires the command_prefix= parameter...
cant look at it RN
this is probably not how you want to do it
its not good practice to sync to the tree everytime
just add a regular bot.command that works with your prefix
to sync instead
ok but you will actually need it for certain stuff at the beginning before you can move away from command prefixes
no, you can ignore the prefix commands
Regular commands are boring, either way adding a tree command won't do any harm to it.
They are a slash command, only way it's actually synced is if it's ran in the proper guild.
not for syncing commands
it will do harm as you get ratelimited very quickly by the endpoint
and why sync if there's no command changes?
for bot development you'll do a lot of relaunches in which you dont necessarily edit command parameters
oh i thought you were asking a question, yeah having a prefix command for syncing is a good use
I have several commands under the same system, never had issues.
you do you, but its literally a day one thing that you learn in on_ready events
that syncing to the tree on launch is unnecessary and nooby
There is stuff for on_ready 🤷
and using a prefix command to sync it is clunky
that is not clunky at all lol?
It works, do you think people care on how their code looks? It still works efficient.
how on earth are you gonna say that using a prefix command to sync things designed to remove prefix commands is not clunky lol
youre not gonna win this argument
I am looking for coding a discord bot
its bad and nooby practice to include automatic tree syncing in on_ready
As said, it works with no issues.
as for this the ratelimit was like 2/30s last i checked, but it won't contribute to your 200 daily command creation rate limit unless you add or rename commands
true, on_connect is better
'if it aint broke dont fix it' mentality
Exactly..?
I dont use discord since I forgot my old discord accounts password but I make bots for a website called hack.chat and I think it is simillar to hack.chat
that is not a good thing
Why would I waste time fixing something that doesn't need fixed?
unless you're paid to make discord bots, not wasting your time fixing stuff that works absolutely is a good thing
You definitely make some garbage bots m8..
Who me?
because i teach you something that is better practice i make garbage bots
not you
@unreal pilot
Clearly you got yourselves hired by a 14 year old for a failed stock replica
Bud you're bashing on me for my structure however either way it works efficiently?
I make my own bots for my own stuff, not for others.
i remember you
remember tango
😭
bro what the fuck is that code
outrageous
Yeah, what about him?
@unreal pilot how iss this outrageous
if you dont know that then youre not ready to develop with discordpy sorry
discordpy is a complicated library
pOGO
Stop. This is a completely unfair way to treat beginners.
Maybe work on organization 🤐
There’s nothing wrong with that 😂
It's just messy, sure it works however the code is over two years old, if you were to repurpose that on a website it wouldn't work 💀
If making bots is why you wanna get into programming make bots. Yes, it's complex, but it's hardly gonna be fun to make stuff you don't care about. Plenty of people have got into development through Discord bots, and it's not our place to tell them they're not worthy of it. I suggest either helping and encouraging, or staying out of it, because convincing beginners that they're not good enough to do the thing inspiring them to develop isn't cool
go to the dpy discord server, and ask the library maintainers if you dont trust me
its not only messy, its bad practice 101
He's saying I'm a noob cause of the way I sync my on_ready, however in the end it works with no issues.
That's the same thing 💀
How is it bad practice
How do you structure your bots?
I'm really struggling to see how syncing upon startup is so terrible honestly, if it were a PUT request overwriting all commands then yeah, I'd understand, but as it is, just GETting all your commands, diffing, and updating ones that are needed is entirely reasonable, sensible even. There's a reason the ratelimit on GET commands is lower than POST/PATCH (or maybe it's PUT I can't remember), and that's because it's an inexpensive operation, which makes it suitable for that sort of use on startup
How do I get a discord bot token?
On the developer site for discord
Discord Developer Portal
Is it free?
Yes
Bot/event loop initializer with cog loaders on the main
Split all bot topics into a cogs folder and subclass from Cog per standalone utility
Seperate utils, database operations, blockchain operations.. you name it
keep cogs purely for discord comms and handle your more complex logic in seperate funcs
is it application id Or public key?
where do I get it?
https://github.com/Robin5605/discord-bot-template usually how I do mine
Nvm found it
I found it already but thanks for offering help
@sick birch what are your thoughts on this? he's saying the structure is nooby, however in the end the code base is fine?
What's your opinion on the way it's synced?
Yes this is how i structure mine on the base level
Code organisation is so important for discord bots
How do i add it to a server
2024-01-18 15:26:15 WARNING discord.ext.commands.bot Privileged message content intent is missing, commands may not work as expected.
2024-01-18 15:26:15 INFO discord.client logging in using static token
2024-01-18 15:26:16 INFO discord.gateway Shard ID None has connected to Gateway (Session ID: 30742bfa6c1cbf519a9dd16cd25dfe1a).
Logged in as IntelliBot
How severe is the rate limit for syncing? I don't think it even matters how you sync if you're not doing it hundreds of time in a single minute 🥴
Go to bot on the developer dashboard, and toggle the intents.
ok
now wut
Restart the bot
ok
I dont understand helping somebody when he doesnt understand the reason behind the actions
You wont learn anything then
2024-01-18 15:30:41 WARNING discord.ext.commands.bot Privileged message content intent is missing, commands may not work as expected.
2024-01-18 15:30:41 INFO discord.client logging in using static token
2024-01-18 15:30:42 INFO discord.gateway Shard ID None has connected to Gateway (Session ID: 56025b8dfc9093e7122585e83aa3c450).
Logged in as IntelliBot
!intents - enable it in your code
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. Various features of discord.py rely on having particular intents enabled, further detailed in its documentation. Since discord.py v2.0.0, it has become mandatory for developers to explicitly define the values of these intents in their code.
There are standard and privileged intents. To use privileged intents like Presences, Server Members, and Message Content, you have to first enable them in the Discord Developer Portal. In there, go to the Bot page of your application, scroll down to the Privileged Gateway Intents section, and enable the privileged intents that you need. Standard intents can be used without any changes in the developer portal.
Afterwards in your code, you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:
from discord import Intents
from discord.ext import commands
# Enable all standard intents and message content
# (prefix commands generally require message content)
intents = Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see discord.py's related guide, and for general information about them, see the Discord developer documentation on intents.
it did nothing even reset the token
See what i mean
Then help them understand 🤷
oh thank you @naive briar
If someone actually doesn't try, then that's another problem
Your being rude
Who cares, it's a server for communication, it's literally a channel where people come to receive help.
import discord
from discord.ext import commands
from discord import Intents
from discord.ext import commands
Enable all standard intents and message content
(prefix commands generally require message content)
intents = Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix="!", intents=intents)
intents = discord.Intents.default()
intents.messages = True
intents.guilds = True
intents.reactions = True
bot = commands.Bot(command_prefix='!', intents=intents)
@bot.event
async def on_ready():
print(f'Logged in as {bot.user.name}')
await bot.change_presence(activity=discord.Game(name='Type !help'))
@bot.command(name='hello', help='Responds with Hello!')
async def hello(ctx):
"""Greets the user."""
await ctx.send(f'Hello, {ctx.author.mention}!')
@bot.command(name='ping', help='Check the bot's latency')
async def ping(ctx):
"""Check the bot's latency."""
latency = round(bot.latency * 1000)
await ctx.send(f'Pong! Latency is {latency}ms')
@bot.command(name='clear', help='Clear messages in the channel')
async def clear(ctx, amount: int):
"""Clear messages in the channel."""
if 1 <= amount <= 100:
await ctx.channel.purge(limit=amount + 1)
await ctx.send(f'{amount} messages cleared by {ctx.author.mention}.', delete_after=5)
else:
await ctx.send('Please provide a number between 1 and 100.')
bot.run(' ')
I used a template
I think its good
it keeps saying no privlegges
It literally says it
in the screenshot I posted
He shouldn't expect to be spoonfed, that's not how you learn
Nvm I misread what you sent
No
then stay out of it /shrug, not your place to be telling others who not to help if they want to help
Thank you guys so much I made my first bot it isnt the best but atleast I did it thank you guys so much
is it possible to make it so no matter what perm level you have youre able to use commands like ban, kick etc with your bot?
Perm level for the bot or the user
the bot has admin and is at the top of the roles list and i would just be a member with no permissions
Yeah it's possible aslong as you give that user perms to use the command
On the bots end
you can, but speaking as a community manager if I found out a bot's owner was going around banning people through their bot even in servers they don't moderate I'd kick the bot and warn everyone I knew not to use it immediately, you shouldn't be claiming jurisdiction over other people's servers like that
Firth that is a weird request I could help you only if its fine with this servers rules and you are using it for ethical purposes
I would only be using it on servers i run/manage incase i was talking on an alt or for any other reason @vocal plover
from discord.ext import commands
bot = commands.Bot(command_prefix='!')
# You can change these if youd like
PERM_LEVEL_ADMIN = 2
PERM_LEVEL_MODERATOR = 1
PERM_LEVEL_USER = 0
def check_permission_level(ctx, required_level):
user_permissions = {'admin_user_id_1': PERM_LEVEL_ADMIN, 'moderator_user_id_2': PERM_LEVEL_MODERATOR, 'regular_user_id_3': PERM_LEVEL_USER}
user_permission_level = user_permissions.get(str(ctx.author.id), PERM_LEVEL_USER)
return user_permission_level >= required_level
@bot.command(name='ban', help='Ban a member (custom permission check)')
async def ban(ctx, member: discord.Member, reason=None):
if check_permission_level(ctx, PERM_LEVEL_MODERATOR):
await member.ban(reason=reason)
await ctx.send(f'{member.mention} has been banned. Reason: {reason}')
else:
await ctx.send('Permission denied.')
@bot.command(name='kick', help='Kick a member (custom permission check)')
async def kick(ctx, member: discord.Member, reason=None):
if check_permission_level(ctx, PERM_LEVEL_MODERATOR):
await member.kick(reason=reason)
await ctx.send(f'{member.mention} has been kicked. Reason: {reason}')
else:
await ctx.send('Permission denied.') #firth thene add anything else youd like ```
Please do not try backdooring any servers using this
tysm, i didnt think youd write it all for me
Then just add bot.run('Your token')
Its not the best code I also used some templates to help me so I didnt do all of it
!codeblock fyi
ok thanks
6 months ago i checked this, and the PUT /applications/{id}/commands endpoint returned a limit of 2 with it resetting after 29.999s
not that significant even if you do get throttled, so i guess setup_hook is okay enough for syncing
I feel like a douche
I have covid and im just sleeping on my bed all day and codingn
Bro's discord account was made today 🫤
Uff, using the new ForumChannel.create_thread() method however discord answers with '''Failed to create forum thread. Error: 400 Bad Request (error code: 50006): Cannot send an empty message
Failed to post the topic.''' code: https://paste.pythondiscord.com/JEMA
https://paste.pythondiscord.com/JEMA#1L84-L84 you need to provide content while creating the thread here, because you can't have an empty thread, you could move your embed from the thread.send call into the create_thread call
also as general improvements, you can apply tags while creating the thread by passing them into the applied_tags arg of the create_thread call, so you don't need a separate API call afterwards
it seems to be working until it it doesn't no more. "Failed to create forum thread. Error: ForumChannel.create_thread() got an unexpected keyword argument 'message'
Failed to post the topic."
what are you passing to it? have you read the docs for what needs to be given to it?
!d discord.ForumChannel.create_thread
await create_thread(*, name, auto_archive_duration=..., slowmode_delay=None, content=None, tts=False, embed=..., embeds=..., file=..., files=..., stickers=..., ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Creates a thread in this forum.
This thread is a public thread with the initial message given. Currently in order to start a thread in this forum, the user needs [`send_messages`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.send_messages).
You must send at least one of `content`, `embed`, `embeds`, `file`, `files`, or `view` to create a thread in a forum, since forum channels must have a starter message.
It seems like you're passing either content or embeds, but trying to provide it as message= when it should be embeds=[] or content="..."
Oh, fixed it. Now only image url has to be passed, but it seems to stay empty ```async def create_forum_thread(channel_id, name, message, image_url=None, tag_ids=None):
channel = bot.get_channel(int(channel_id))
if not channel or not isinstance(channel, discord.ForumChannel):
print(f"Channel {channel_id} is not a ForumChannel or not found.")
return False
try:
# Prepare the embed with the image (if provided)
embed = None
if image_url:
embed = discord.Embed(description=message)
embed.set_image(url=image_url)
# Create a thread with the initial message and/or embed
thread = await channel.create_thread(
name=name,
auto_archive_duration=10080,
content=message if not embed else None,
embed=embed
)
# Apply tags to the thread if they exist
if tag_ids:
tag_objects = [discord.Object(id=tag_id) for tag_id in tag_ids]
await thread.edit(applied_tags=tag_objects)
return True
except Exception as e:
print(f"Failed to create forum thread. Error: {e}")
return False```
everything else comes through
In message.embeds.0.image.url: Not a well formed URL.
Failed to post the topic.```
!format
could it be (url=image_url) not getting handeled correctly?
as at the start of the script when printing it gets returned correctly
thank you @unreal pilot ! ```smiley
im making a logger that logs every message with my bot
how do i make it ignore certain channels/categories/members/servers?
@bot.event
async def on_message(message):
channel = bot.get_channel(1197588840421019748)
await channel.send("{} in {}: {}".format(str(message.author), message.guild.name, message.content))
this is what i have, i just want it to ignore this channel id (1197588840421019748)
as a rule of thumb, you should always ignore bots:
if message.author.bot:
return
tyty, that does seem very logical
currently trying to make a command that clears 500 of my messages but im not sure how to filter it to only clear my messages
@bot.command()
async def m(ctx, amount: int = 500):
if ctx.message.author.id == firthid:
await ctx.channel.purge(limit=amount+1)
else:
return
is there like a way to check if the message is sent by a certain id
@tree.command(name='change_avatar', description='Change The Profile Picture Of The Discord Bot', guild=discord.Object(id=server_id))
async def change_avatar(interaction, url_of_image: str):
await client.user.edit(avatar=url_of_image)
embed = discord.Embed(title='Successfully Changed Avatar', color=discord.Color.blue()).set_thumbnail(url=url_of_image)
await interaction.response.send_message(embed=embed)
when i execute the command i get the error
discord/app_commands/commands.py", line 842, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'change_avatar' raised an exception: TypeError: startswith first arg must be str or a tuple of str, not bytes
can someone help?
!d discord.TextChannel.purge
await purge(*, limit=100, check=..., before=None, after=None, around=None, oldest_first=None, bulk=True, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Purges a list of messages that meet the criteria given by the predicate `check`. If a `check` is not provided then all messages are deleted without discrimination.
You must have [`manage_messages`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_messages) to delete messages even if they are your own. Having [`read_message_history`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.read_message_history) is also needed to retrieve message history.
Changed in version 2.0: The `reason` keyword-only parameter was added.
Examples
Deleting bot’s messages...
note the check= kwarg
accepts a callable that has a Message object as its input and a Boolean as its output
2024-01-18 18:55:35 ERROR discord.client Attempting a reconnect in 0.20s
Traceback (most recent call last):
File "/home/container/.local/lib/python3.9/site-packages/discord/client.py", line 659, in connect
await self.ws.poll_event()
File "/home/container/.local/lib/python3.9/site-packages/discord/gateway.py", line 646, in poll_event
raise ConnectionClosed(self.socket, shard_id=self.shard_id, code=code) from None
discord.errors.ConnectionClosed: Shard ID None WebSocket closed with 1000
``` why is it reconnecting?
@bot.command()
async def m(ctx, amount: int = 500):
if ctx.message.author.id == firthid:
await ctx.channel.purge(limit=amount+1, check=firthid)
else:
return
like that?
does any1 have a slash command discord bot template
What is firthid? Is it a function that accepts a Message object and returns a boolean?
its a variable with my userid
firthid = 719211519359058070
which im guessing is not how check works
well, check accepts a function that accepts a Message object and returns a bool
discord.py will call the function you provide and if it returns True, then it will delete the message. If it doesn't, then it won't
this is what I use: https://github.com/Robin5605/discord-bot-template
feel free to modify it however you wish for app commands
thanks
so id have to have a function that checks if the message is sent by my userid?
im not really sure how to code that and ive searched it on google and i cant get anything
import discord
from discord_slash import SlashCommand
client = discord.Client(intents=discord.Intents.all())
slash = SlashCommand(client, sync_commands=True)
@client.event
async def on_ready():
print("Ready!")
client.run('')
error:
from discord_slash import SlashCommand # Importing the newly installed library.
ModuleNotFoundError: No module named 'discord_slash'
how do i fix it, i've tried everything
sure, that sounds like one way
personally since it's just a really simple one line function I'd just do a lambda but you don't have to
can any1 help
I have this command where badically what it does is where every single server has there own RC which is just a number, if a server runs the command twice instead of adding that number onto the list, it just updates it since the server ran it 2 times. But the problem I am having is that every single time that the bot restarts and a server who already did the command does it again, it adds on to the list instead of updating the list
so basically what im trying to do is regardless if i restart the bot or not, in my list there should not be 2 of the same id's, it should just update it
@bot.command()
async def firth(ctx, amount: int = 500):
if not ctx.message.author.id == firthid:
return
to_delete = []
async for m in ctx.channel.history(limit=amount+1):
if m.author.id == firthid:
to_delete.append(m)
if len(to_delete)==100:
await ctx.channel.delete_messages(to_delete)
to_delete=[]
if to_delete:
await ctx.channel.delete_messages(to_delete) ```
ended up using that, a bot dev i know made it
i mean, that's a really roundabout way to do purge but ok
guys i need help, i can surely load the cogs but if its a slash command cog it doesnt show up on the slash commands list:
import discord
from discord.ext import commands
import subprocess
import importlib
import sys
import os
class Reload(commands.Cog):
def __init__(self, bot: commands.Bot):
self.bot = bot
@commands.slash_command(name='reload', guild_ids=[1184567083363745862])
async def _reload(self, ctx):
if ctx.author.id == 397747000709349377:
botMessage = await ctx.respond("Please wait...", ephemeral=True)
await botMessage.edit_original_response(content=f"Update complete - loading modules...")
# Reload all loaded cogs
for filename in os.listdir("./cogs"):
if filename.endswith(".py"):
cog_name = f"cogs.{filename[:-3]}"
try:
if cog_name not in self.bot.extensions:
self.bot.load_extension(cog_name)
await botMessage.edit_original_response(content=f"Loaded {cog_name}")
else:
self.bot.reload_extension(cog_name)
await botMessage.edit_original_response(content=f"Reloaded {cog_name}")
# self.bot.reload_extension(cog_name)
# await botMessage.edit_original_response(content=f"Reloaded {cog_name}")
except Exception as e:
await ctx.send(f"Failed to reload {cog_name}: {e}")
await self.bot.sync_commands() ##here it gives errors too
await botMessage.edit_original_response(content=f"Reloading complete.")
def setup(bot):
bot.add_cog(Reload(bot))
You sync the commands at some point when starting the bot at least, right?
can someone take a look at my scripts and help me find out why the .py I'm trying to import into my main script won't be recognized or initialized?
class OPBot(commands.Bot):
def __init__(self) -> None:
super().__init__(command_prefix = ".", intents = intents)
async def onready(self):
await self.wait_until_ready()
print(f"Bot {bot.user.name} is now online")
async def setup_hoop(self):
for name in os.listdir("cogs."):
if name.endswith(".py"):
try:
await self.load_extension(f"cogs.{name[:-3]}")
print(f"The Commands in file cog.{name[:-3]}")
except Exception as error:
print(f"This file cant be loaded Pleas fix this error \n {error}")
bot = OPBot()
cogs dont work
doesnt recognize the commands
Hi , how can I make that everytime there is someone sending a message in a specific channel , my bot sends a messsage like @friend
you can use the on_message event
but instead, you can check if message.channel.id == your channel ID: and do stuff inside that if
im completlyt new to coding is there any video that could help me with that code ?
nvm i just realized
The unfortunate reality is that when it comes to discord.py, most videos aren't good. Most show bad practices, and could generally be misleading. And with the fast nature of the discord API, they tend to be out-of-date fairly quickly, so putting effort into making a good one is unfortunately pointless.
The best thing to do is first, try picking up the python basics before doing something complex like a discord bot. After that, the best place to help yourself is the official examples and documentation. (see this channel's topic)
See the main page of the docs. Especially the Getting Started section:
https://discordpy.readthedocs.io/en/latest/index.html
@client.event
async def on_ready():
async with aiosqlite.connect("main.db") as db:
async with db.cursor() as cursor:
await cursor.execute(
'CREATE TABLE IF NOT EXISTS users (settransactionschannel STRING, setlogschannel STRING, setalertschannel STRING, setgametimechannel STRING, setpickupschannel STRING, setstreamschannel STRING, setfreeagencychannel STRING, setnoticeschannel STRING, setverdictschannel, guild INTEGER, setdemandchannel STRING)'
)
await db.commit()
async with aiosqlite.connect("main.db2") as db2:
async with db2.cursor() as cursor:
await cursor.execute(
'CREATE TABLE IF NOT EXISTS users (setrefereerole STRING, setcandidaterole STRING, setcaptainrole STRING, setsuspendedrole STRING, setstreamerrole STRING, guild INTEGER, seteligiblerole STRING)'
)
await db2.commit()```
```py
async with aiosqlite.connect("main.db2") as db2:
async with db2.cursor() as cursor:
await cursor.execute(
'SELECT setrefereerole FROM users WHERE guild = ?',
(ctx.guild.id, ))
data = await cursor.fetchone()
if not data:
pass
else:
refrole = ctx.guild.get.role(int(data[0]))```
```py
if refrole is not None:
refrole = refrole.mention
else:
refrole = "None"```
I set the role and it keeps returning as none it doesnt do this for any of the other ones like setcaptainrole or any of them so im really confused, maybe im not saying something im supposed to idk
Yes, when the bot gets restarted it loads all the commands. Though I'm trying to make it so I don't have to stop the bot every time I add a new cog, so i won't ruin the asyncio processes that it have currently running.
can you give me example?
congrats! which project did you start with?
Why do people like context managers this much, code is overindented
Also yeah gonna recommend some code design improvements
But to actual issue
Browse the second db and see if the row is there. You don't have a primary key which is kinda bad too
And show how you insert the role
Shouldn't there be an UnboundLocalError here or something? 
And now to design issues and heck they are major
- You DO NOT need 2 databases. No matter the case, you DO NOT need 2 databases. I'm just completely sure about this, either merge two tables' columns together or create a separate table in main database. However if you have some
messed upcomplex databases system that is shared among several projects you can keep it this way - One connection. Do not create connection every time you need to make a query. Instead, subclass your bot
class MyBot(commands.Bot):
db: aiosqlite.Connection
async def setup_hook(self):
self.db = await aiosqlite.connect("main.db")
async def close(self):
await self.db.close()
await super().close()
async def execute(self, query: str, args: tuple) -> aiosqlite.Cursor:
# I forgot how it's done in aiosqlite but from what I remember this way, refer to docs or test to be sure
cur = await self.db.execute(query, args)
await self.db.commit()
return cur
bot = MyBot(...)
- SQL script. Instead of hardwriting
CREATE TABLEinto python code, bring them out to a separate.sqlfile and execute contents of the file on initialization. You can format the file nicely so you don't get confused.
Generally would recommend to look at my old birthday bot. Has some flaws and is not in dpy but good for understanding how to connect and use database in a better way
Yeah there's Connection.executescript() method now so you don't need that ugly for loop for file executing, can just pass entire file content
anyone know how to code or what's the code for a auto delete user msg bot
Please don't use headers for no reason. Answering the actual question, yes, plenty of people do ☺️
can u help me
With what ☺️
how do i make it to where my bot auto deletes all the messages of a certain user's ID when they type
Listen to on_message and compare message.author.id to that certain user's ID
wait wym
Well I am feeling spoon feeding so I am gonna spoonfeed
🙏🏼
import discord
client = discord.Client(intents=discord.Intents(message_content=True, guild_messages=True))
@client.event
async def on_message(message: discord.Message):
if message.author.id == USER_YOU_WANNA_BULLY_ID:
await message.delete()
client.run("TOKEN")
Very minimal, not even using commands framework 👁️👄👁️
@vale wing oh snap
if you don’t mind me asking, what’s your opinion on selfbots.
fr
will this work on a user acc
some are useful
some funny too
but some are just un needed
The lib just doesn't support selfbots
And we ain't helping with selfbots here
ohhh so does that code work for a regular bot
Yep
how do i get it to work with a regular bot so the bot delete the msg
By replacing corresponding things in that code, setting up environment and running it
I ain't wanna spoonfeed that sry
Yes
😃
alr
How can i get Error's full traceback from on_command_error(ctx, error)
You can use the traceback lib
I struggled with fetching traceback from on_command_error cause for some reason error.__traceback__ was None. However yours is not so you can use traceback lib yeah
s = traceback.format_exc(error)
Thanks for help
RuntimeWarning: coroutine 'BotBase.load_extension' was never awaited
!e RuntimeWarning: coroutine 'BotBase.load_extension' was never awaited
@hazy kraken :x: Your 3.12 eval job has completed with return code 1.
001 | File "/home/main.py", line 1
002 | RuntimeWarning: coroutine 'BotBase.load_extension' was never awaited
003 | ^^^^^^^^^^^^^^^^^^^^^^^^
004 | SyntaxError: invalid syntax
The error is very clear
Yes you have to await the function call. If you don't know what await is you should probably learn about about async before making bots
import os
import asyncio
import discord
from dotenv import load_dotenv
from discord.ext import commands
# Intents
intents = discord.Intents.all()
client = commands.Bot(command_prefix="m.", intents=intents, help_command=None)
# Load Cogs
async def load_extensions():
for filename in os.listdir('./cogs'):
if filename.endswith('.py'):
await client.load_extension(f'cogs.{filename[:-3]}')
# Load Tokens
load_dotenv()
token = os.getenv('MOMO_TOKEN')
async def main():
async with client:
await load_extensions()
await client.start(token)
asyncio.run(main())
- why would run a python bot using npm
- also you sure u have installed the correct discord library
discord.pyand don't have other forks installed simultaneously?
!pypi discord.py
I use that so that when I edit the document it runs automatically
fair i suppose i have a custom function under my bot class which does that for me when i edit cogs
which one you use?
yes
I have used a few of them so far ones discord.py and disnake are the ones that stand out for me mostly
disnake has hot reloading with cogs so thats a feature i liked a lot so i ported it over to discord.py
I feel like npm just doesn't activate the venv
i see
pip install discord.py
Instead of python bot.py try venv/Scripts/python.exe bot.py
before worked for me.
Or bin depending if you're on unix
im in windows
or u can just activate the venv and run the npm command (assuming the bot command is hard to edit or configure)
Yeah
Oh nvm I thought the module was not found
You have installed something else thah discord.py
It's an outdated library most definitely
. @hazy kraken
yes i made
pip freeze
also might wanna pip freeze and remove unwanted packages using pip uninstall
just run this script ```py
import os
import sys
py_exec = sys.executable
uninstall_list = " -m pip uninstall nextcord py-cord interactions.py disnake dislash discord-py-slash-command discord.py-message-components enhanced-discord.py novus hata discord-interactions discord.py-self discord.py-self.embed discord2 python-discord reactionmenu discord_py_buttons discord_slash discord.py discord discord-ext-forms discord-ext-alternatives dpy-appcommands discord-ext-slash"
os.system(py_exec + uninstall_list)
os.system(py_exec + " -m pip install discord.py --no-cache-dir")
PS C:\Users\zhiya\Desktop\BOT de discord\momo-bot> pip list
Package Version
------------------ ------------
aiohttp 3.8.6
aiosignal 1.3.1
annotated-types 0.6.0
anyio 4.2.0
async-timeout 4.0.3
asyncpg 0.29.0
attrs 23.1.0
certifi 2023.11.17
charset-normalizer 3.3.2
colorama 0.4.6
crash 0.30.1
crate 0.34.0
discord.py 2.3.2
distlib 0.3.8
distro 1.9.0
exceptiongroup 1.2.0
filelock 3.13.1
frozenlist 1.4.1
h11 0.14.0
httpcore 1.0.2
httpx 0.26.0
idna 3.6
multidict 6.0.4
mysql-connector 2.2.9
mysqlclient 2.2.1
nodemon-py-simple 0.0.7
numpy 1.26.3
openai 0.28.1
pandas 2.1.4
pip 23.3.2
pipenv 2023.11.15
platformdirs 4.1.0
prompt-toolkit 3.0.43
py-cord 2.0.0b7
py-mon 2.0.3
pydantic 2.5.3
pydantic_core 2.14.6
pygame 2.5.1
Pygments 2.17.2
pymon 1.1
python-dateutil 2.8.2
python-dotenv 1.0.0
pytz 2023.3.post1
requests 2.31.0
setuptools 69.0.3
six 1.16.0
sniffio 1.3.0
sqlparse 0.4.4
tabulate 0.9.0
toml 0.10.2
tqdm 4.66.1
typing_extensions 4.9.0
tzdata 2023.4
urllib3 2.0.7
virtualenv 20.25.0
watchdog 3.0.0
wcwidth 0.2.12
yarl 1.9.4
PS C:\Users\zhiya\Desktop\BOT de discord\momo-bot>
py-cord
how to put this
Put into python file and run it
alr
this?
Yea
alr
Yeah bro got both pycord and discord.py
i see-
Yea i dont understand that language
Just re-create the venv who knows what other sheep they got there
But just uninstall py-cord
oki
(.venv) PS C:\Users\zhiya\Desktop\discord BOT\momo-bot> python script.py
"C:\Users\zhiya\Desktop\BOT" is not recognized as an internal or external command, executable program or batch file.
"C:\Users\zhiya\Desktop\BOT" is not recognized as an internal or external command, executable program or batch file.
(.venv) PS C:\Users\zhiya\Desktop\discord BOT\momo-bot>
also just listing all the packages name to uninstall looks funny to me
ur file path has a space in it which causes it to be unable to find the executable
u can instead do this
venv/Scripts/activate.bat
pip uninstall pycord
first like activates the venv in the current terminal and second line uninstalls pycord
i cant-
gave me error here
thats fine its not an error
u can try running the bot now
pip install python-dotenv
also make sure venv is enabled before any install process u run in the future same when ur running the bot
again
venv is off
enable it
to check if ur venv is on ur CLI will be prefixed like (momo-env)
now run the npm command
always active the venv before running any commands
can u help me with the sourcing of the cogs -
tbh just use python to directly run the bot node seems painful here
look
i've
a folder called Cogs
inside of this folder i've 3 sub-folders: Events, prefixCommands, slashCommands
then inside of each folder i've the files of my cogs
i'm trying to doing this
async def load_extensions():
for folder in os.listdir('./cogs'):
if os.path.exists(os.path.join('./cogs', folder, )):
await client.load_extension(f'cogs.{folder[:-3]}')
thats not how u load cogs its partially correct ur pointing to the folder containing the cogs u need to point to the individual cogs as files instead
the fact is that idk how ..
so u would have to recursively or through some other method get all files in the directory
how to do it recursively?
!d glob.glob
glob.glob(pathname, *, root_dir=None, dir_fd=None, recursive=False, include_hidden=False)```
Return a possibly empty list of path names that match *pathname*, which must be a string containing a path specification. *pathname* can be either absolute (like `/usr/src/Python-1.5/Makefile`) or relative (like `../../Tools/*/*.gif`), and can contain shell-style wildcards. Broken symlinks are included in the results (as in the shell). Whether or not the results are sorted depends on the file system. If a file that satisfies conditions is removed or added during the call of this function, whether a path name for that file will be included is unspecified.
!d os.walk
os.walk(top, topdown=True, onerror=None, followlinks=False)```
Generate the file names in a directory tree by walking the tree either top-down or bottom-up. For each directory in the tree rooted at directory *top* (including *top* itself), it yields a 3-tuple `(dirpath, dirnames, filenames)`.
either method works
should be like this right?
C:\Users\zhiya\Desktop\BOT de discord\momo-bot\bot.py:25: RuntimeWarning: coroutine 'BotBase.load_extension' was never awaited
client.load_extension(cog_name)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
Loaded cogs.Events.events
Loaded cogs.prefixCommands.help
Loaded cogs.prefixCommands.ping
Loaded cogs.prefixCommands.purge
Loaded cogs.prefixCommands.randome
Loaded cogs.slashCommands.Reacciona
await it
Oh yall finally got through this 💀
yes-
and the terminal send this error
> bot-main@1.0.0 dev
> nodemon bot.py && cls
[nodemon] 3.0.3
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: py,json
[nodemon] starting `python bot.py`
C:\Users\zhiya\Desktop\BOT de discord\momo-bot\bot.py:25: RuntimeWarning: coroutine 'BotBase.load_extension' was never awaited
client.load_extension(cog_name)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
Loaded ./cogs/Events/events.py
Traceback (most recent call last):
File "C:\Users\zhiya\Desktop\BOT de discord\momo-bot\momo-env\lib\site-packages\discord\ext\commands\bot.py", line 958, in _resolve_name
return importlib.util.resolve_name(name, package)
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.3056.0_x64__qbz5n2kfra8p0\lib\importlib\util.py", line 32, in resolve_name
raise ImportError(f'no package specified for {repr(name)} '
ImportError: no package specified for './cogs\\Events\\events.py' (required for relative module names)
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\zhiya\Desktop\BOT de discord\momo-bot\bot.py", line 40, in <module>
asyncio.run(main())
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.3056.0_x64__qbz5n2kfra8p0\lib\asyncio\runners.py", line 44, in run
return loop.run_until_complete(main)
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.3056.0_x64__qbz5n2kfra8p0\lib\asyncio\base_events.py", line 649, in run_until_complete
return future.result()
File "C:\Users\zhiya\Desktop\BOT de discord\momo-bot\bot.py", line 38, in main
await load_extensions()
File "C:\Users\zhiya\Desktop\BOT de discord\momo-bot\bot.py", line 30, in load_extensions
await client.load_extension(cog_path)
File "C:\Users\zhiya\Desktop\BOT de discord\momo-bot\momo-env\lib\site-packages\discord\ext\commands\bot.py", line 1005, in load_extension
name = self._resolve_name(name, package)
File "C:\Users\zhiya\Desktop\BOT de discord\momo-bot\momo-env\lib\site-packages\discord\ext\commands\bot.py", line 960, in _resolve_name
raise errors.ExtensionNotFound(name)
discord.ext.commands.errors.ExtensionNotFound: Extension './cogs\\Events\\events.py' could not be loaded.
[nodemon] app crashed - waiting for file changes before starting...
Package name should be like cogs.Events.events, not the filename
Haven't awaited it
Line 9 for example
And not sure what line 14 is supposed to do but yeah
the whole code
^
And you might want to reset your token now
me?
not understanding
yes ill do it
--- idk why .. the dotenv not working anymore
ImportError: cannot import name 'load_dotenv' from 'dotenv' (C:\Users\zhiya\Desktop\BOT de discord\momo-bot\momo-env\lib\site-packages\dotenv_init_.py)
you mean this??
Precisely
but still giving me .. error
is like .. is not reading.. the directory
Do this
import pathlib
for p in pathlib.Path("cogs").glob("**/*.py"):
await bot.load_extension(p.as_posix()[:-3].replace("/", ".")(
i sustituit by what?
That's slicing
async def load_extensions(folder="./cogs"):
for subdir, _, files in os.walk(folder):
for file in files:
if file.endswith(".py"):
cog_path = os.path.join(subdir, file)
cog_name = cog_path.replace(os.sep, "/").replace(".py", "")
try:
await client.load_extension(cog_name)
print(f"Loaded {cog_name}")
except Exception as e:
print(f"Failed to load {cog_name}: {e}")
by
for file in files:
if file.endswith(".py"):
cog_path = os.path.join(subdir, file)
cog_name = cog_path.replace(os.sep, "/").replace(".py", "")
Hey! I want to make a smart leaderboard that updates every 10 minutes.
But the problem is that my bot is public, and I want to know what is the best way to do it with hundreds of servers.
Make sure your setup()s and add_cog()s are async
Alr
Make a loop and just fetch the data?
In typical database it would look like
SELECT id, score FROM guilds ORDER BY score DESC LIMIT 10```
ik i have already done the leaderboard
So you only want the background loop?
!d discord.ext.tasks.loop check entire page, there are plenty of examples
@discord.ext.tasks.loop(*, seconds=..., minutes=..., hours=..., time=..., count=None, reconnect=True, name=None)```
A decorator that schedules a task in the background for you with optional reconnect logic. The decorator returns a [`Loop`](https://discordpy.readthedocs.io/en/latest/ext/tasks/index.html#discord.ext.tasks.Loop).
what's reconnect do?
You want to update the lb in each server or smth?
Everything's in docs
in each server
finally works tysm
I have done it, but the loop doesn't work
@tasks.loop(seconds=10)
async def smartleaderboard(self):
print("1")
async with aiosqlite.connect("main.db") as db:
async with db.cursor() as cursor:
guild_db = await cursor.execute("SELECT guild FROM servers")
guild_ids = await guild_db.fetchall()
for guild_id in guild_ids:
.....
it prints "1" but didn't edit the message... can I send u the full code in dms?
this is the loop start:
# while on_ready event
if not self.smartleaderboard.is_running():
self.smartleaderboard.start()```
- You are planning to do a very expensive operation every 10 seconds. Change it to 10 minutes at least
- No ORDER BY clause
Do not send me code in dms, instead use pasting service
!paste
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.
Regarding style of your aiosqlite code, check [this](#discord-bots message), 2nd point
Discord is the easiest way to communicate over voice, video, and text. Chat, hang out, and stay close with your friends and communities.
I put it in a 10 second queue so that I don't have to wait every time to check that it edits the message. There is an ORDER BY later in the code.
Okay send full code
With this
I’m having a problem in the interaction on a Selection
here's the relevant code.
Ok will check that
ty
Also start the loop in init
You checked the examples in doc I linked?
There's an example for cog which shows precisely what I mean
On top of page jic
@dense coral could you also send database structure
class Smartleaderboard(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.smartleaderboard.start()```
you mean like this?
Is there any way I could add the emojis in an easier way? They must be in the order: top, jungle, mid, adc, support for each team.
role_emojis = [':top:', ':jungle:', ':mid:', ':adc:', ':support:']
embed.add_field(name=":crossed_swords: Custom Team 1",
value=f"".join(f"\n> {role_emojis[i]} {u['member'].mention}" for i, u in enumerate(team_1)),
inline=True)
embed.add_field(name=":crossed_swords: Custom Team 2",
value=f"".join(f"\n> {role_emojis[i]} {u['member'].mention}" for i, u in enumerate(team_2)),
inline=True)
Not working the commands
Yep
It's not a problem with the database, when I checked the leaderboard without a loop it worked well.
No I just need the structure to understand what you are even doing there
That thing can be optimized a lot I'm pretty sure
"CREATE TABLE IF NOT EXISTS servers (message ID, info TEXT, users TEXT, votes INTEGER, guild ID)" #table to save all servers and their votes (like top.gg), the message is the vote message
"CREATE TABLE IF NOT EXISTS smartleaderboards (channel INTEGER, message INTEGER, guild ID)" # save all the smart leaderboards to update them easy and check if there is already one of each server.
I have this information if it'll help u
Those if chains scare me
What's the ID datatype? It must be INTEGER maybe?
Also no PK in both tables
But idk why … not reading the commands
It's the same as INTEGER, but it works.
Is MySQL?
Sqlite
Ooh
what is PK?
Primary key
You have settings unique to guild ID? Need a PK on guild id. PK, similarly to UNIQUE constraint, prevents multiple rows with same value in constrained column
does anyone know why i am getting an invalid token error when i use the correct token?
Bot or user token? 🤨
inb4 it's the client secret
bot token.
Ok but is this what is causing the problem?
How can I make two fields next to each other of total 4 fields?
third field is invisible characters
like \u200b (note that this looks dogshit on mobile)
could also be simply two fields
Hahah I know. Is there no other way to do it?
i think this is the best option, that would look decent-ish on mobile
Something like this?
{
name: "Custom Team 1",
value: "@Beerhunter (1545)\n\n**Summoner Name**\nThe Beerhunter #EUW",
inline: true
},
{
name: "Custom Team 2",
value: "@Sami (1659)\n\n**Summoner Name**\nSami #EUW",
inline: true
},
Mhm intresting, thanks @pale zenith
no problem
2024-01-19 16:55:28 ERROR discord.client Attempting a reconnect in 1.62s
Traceback (most recent call last):
File "/home/container/.local/lib/python3.9/site-packages/discord/client.py", line 659, in connect
await self.ws.poll_event()
File "/home/container/.local/lib/python3.9/site-packages/discord/gateway.py", line 646, in poll_event
raise ConnectionClosed(self.socket, shard_id=self.shard_id, code=code) from None
discord.errors.ConnectionClosed: Shard ID None WebSocket closed with 1000
why is it reconnecting
WARNING discord.gateway Can't keep up, shard ID None websocket is 24.5s behind.
commit names are awesome
self-explainatory
Aww thanks
Yess, I did for knowing which changes i made and learn about my errors
Will u help me … with the interaction of my command help … when I’m arriving home
whats exactly the problem?
hey all!
noob to this server but not new to discord or python. I have a bunch of command line code that interacts with discord via webhooks and request.gets with hard-coded authorization in headers... but am ready to move to a proper bot.
Is there a "bot getting started" guide here?
so glad to have found this! Thanks in advance?
Best commit
Free bobux command!
wow nice i had such idea some time ago to create embeds in discord directly with components it provides but abandoned it idk why tbh
based
@client.tree.command(name="add_dev", description="Gives Dev Roles")
async def count_interaction(interaction: discord.Member):
Member.add_roles(id="1197257756038680696")
await interaction.response.send_message("Given Role!")
its not working
This is so wrong the only thing I can do is spoonfeed 😭
Why is interaction typehinted as discord.Member 😭
is this supposed to be a context menu
im not sure im new
What do you want the command to do
give a player a role
Is this command that displays in "apps" when you right click user/message
Or just slash
im trying to make it do /add_role [username]
Okay. The format for slash command callback parameters is the first argument is always going to be interaction: discord.Interaction (unless it's inside a class, in which it'll have self like usual) - then followed by each slash command argument and it's type. In your case, since you want to accept a user, you'll be accepting a discord.Member:
async def add_role(interaction: discord.Interaction, member: discord.Member):
...
In what senario would this occur? Where a bot can NOT add reactions to a users message?
Because im thinking the bot can't add reactions because the user has it blocked? But I don't know if that can mess with it..?
besides blocking the bot or not having the add reactions permission, i'm not aware of any other ways it can fail
alr ty
2024-01-19 16:55:28 ERROR discord.client Attempting a reconnect in 1.62s
Traceback (most recent call last):
File "/home/container/.local/lib/python3.9/site-packages/discord/client.py", line 659, in connect
await self.ws.poll_event()
File "/home/container/.local/lib/python3.9/site-packages/discord/gateway.py", line 646, in poll_event
raise ConnectionClosed(self.socket, shard_id=self.shard_id, code=code) from None
discord.errors.ConnectionClosed: Shard ID None WebSocket closed with 1000
why is it reconnecting
WARNING discord.gateway Can't keep up, shard ID None websocket is 24.5s behind.
Do you think it looks clean?
yea that looks good to me
perhaps make the top part more compact somehow
What do you mean?
I don't like this empty space
is that "Queue Popped!" message important? if it isn't it could be removed
@young dagger 
That is due to the total width. What if I add 'Lobby Creator' next to 'Elo Difference'? Do you think that could work?
How to setup premium in discord.py?
Like the coding part, I got the dev portal part.
the premium/entitlement features are still in master branch, and i think the release was being postponed for a discord change? not sure when the next release will happen, but for now you'll have to install from the repository to use entitlements
i believe this commit contains the changes for it, but you can also see the latest docs like Interaction.entitlements and InteractionResponse.require_premium()
I am confused asf 
confused about what?
wanting to know how to make a command be premium, and if discord has a way to check if the user is premium..?
Thats what im talking abt.
if you have the development version installed from the discord.py repo, i assume you can check Interaction.entitlements to see if they paid for a particular Stock-Keeping Unit, and if not you can use interaction.response.require_premium() to tell them that it's premium
weird that the commit didnt include an app_commands.check for convenience
So there is a development version? So I have to have that development version of discord.py to use Premium related things?
"development version" really means installing directly from the git repository
for example pip install git+https://github.com/Rapptz/discord.py for the latest commit, or for installing a specific commit, pip install git+https://github.com/Rapptz/discord.py@cb3ea9b889dcdefa5aa81b1dc7ce4e3e87abeeb0
So I would need the development version tho right?
either pinned to this commit or anything afterwards
So I should just do pip install git+https://github.com/Rapptz/discord.py@cb3ea9b889dcdefa5aa81b1dc7ce4e3e87abeeb0? Then look at docs on how to do it?
So, it does have an auto check correct?
based on the discord api docs no, your code has to check the entitlements manually
https://discord.com/developers/docs/monetization/entitlements#using-entitlements-in-interactions
thats why i was wondering why there wasn't an app_commands.check to make it a bit easier
Is there any examples?
doesnt look like it
hm...
huh, api docs you're only allowed to publish one SKU, so i guess thats why they dont allow specifying a particular SKU with require_premium()
well regardless, just based on their documentation i assume you'd use it like: ```py
@tree.command()
async def my_command(interaction):
has_premium = False
for entitlement in interaction.entitlements:
if entitlement.sku_id == 1234:
has_premium = True
if not has_premium:
return await interaction.response.require_premium()``` `discord.utils.get()` would make it a bit simpler too
This is lowkey annoying too cuz you have to have a verified bot to test this stuff on n stuff
curiously there's Interaction.entitlement_sku_ids but it checks for entitlement_skus in the interaction payload which isn't documented on the discord API
which is like more down time ya know lol
is it hard to integrate chatgpt into a discord bot?
No
No, its like 20 lines or sum 😭
depending on what you are doing, its really simple.
An error occurred while extracting information: An error occurred while extracting information: [0;31mERROR:[0m Unable to extract [0;34muploader id[0m
on the technical side: no
on the financial side: maybe
so back to my wordle command as i have some free time so i get into it and i wanted to change the footer when someone got the answer or lost so i have added this code to my function that changes the embed:```py
def update_embed(embed: discord.Embed, guess: str) -> discord.Embed:
puzzle_id = int(embed.footer.text.split()[16])
answer = popular_words[puzzle_id]
colored_word = generate_color_word(guess, answer)
empty_slot = generate_blanks()
embed.description = embed.description.replace(empty_slot, colored_word, 1)
try:
if guess == answer:
num_empty_slots = embed.description.count(empty_slot)
if num_empty_slots == 0:
embed.footer(text="\n\nPhew!")
if num_empty_slots == 1:
embed.footer(text="\n\nGreat!")
if num_empty_slots == 2:
embed.footer(text="\n\nSplendid!")
if num_empty_slots == 3:
embed.footer(text= "\n\nImpressive!")
if num_empty_slots == 4:
embed.footer(text="\n\nMagnificent!")
if num_empty_slots == 5:
embed.footer(text= "\n\nGenius!")
elif num_empty_slots == 0:
embed.footer(text=f"\n\nThe answer was {answer}!")
return embed
except Exception as e:
print(e)
traceback.print_exc()```
at the start i got no error so i added the traceback and still no error...
i dont really know what to do..
this is my command code:
https://paste.pythondiscord.com/SOEQ
ah.
im going to take a hard pass on that then
An error occurred while extracting information: An error occurred while extracting information: [0;31mERROR:[0m Unable to extract [0;34muploader id[0m
2024-01-19 16:55:28 ERROR discord.client Attempting a reconnect in 1.62s
Traceback (most recent call last):
File "/home/container/.local/lib/python3.9/site-packages/discord/client.py", line 659, in connect
await self.ws.poll_event()
File "/home/container/.local/lib/python3.9/site-packages/discord/gateway.py", line 646, in poll_event
raise ConnectionClosed(self.socket, shard_id=self.shard_id, code=code) from None
discord.errors.ConnectionClosed: Shard ID None WebSocket closed with 1000
why is it reconnecting
WARNING discord.gateway Can't keep up, shard ID None websocket is 24.5s behind.
question regarding database schema and storing variables of unfixed data type, if anyone could take a glance:
https://discordapp.com/channels/267624335836053506/1198183954784731166/1198183954784731166
You mentioned that "an event can be practically anything" which is totally wrong. The events your bot can handle are limited and you are to define them.
Regarding unfixed amount of keys there are several solutions
- Just switch to json-like db like mongo
- Use JSON data type (from what I saw your engine supports that). If it doesn't, you can always store it as plain text lol
- Create some table with
guild,key,typeandvaluecolumns. Essentially any data can be interpreted as text and all you have to do is convert it based on type.
I strongly feel like you have xy problem rn and the desired result can be reached in another way
An event can be practically anything tho (yeah, ik I'd need to write the code for it).. I could make it so that, on the click of a button, my garage door opened/closed (I don't actually have a garage, just saying).
- Is pretty much what I did, yeah. 1 and 3 are other options which I've considered, as listed in my comment. Question is, what's "better"?
Could be xy, but in what other way could I reach this result? That's the question
Still, event does not mean "anything", but rather "anything that bot can do", "anything that I coded". As for what's better, I'd say whatever produces cleaner code both in SQL and in python. Are you sure that number of keys is floating and not just some guilds have certain keys and some do not?
What feature are you trying to implement
The point is that guild mods should be able to add variables on their own via events (maybe this is a bad word because of its context in the library, I just mean a set of defined instructions) or manually through a simple gui, and then use those variables for executing other events
That's the thing, the list of features isn't fully defined yet and will be expanding. I was explicitly told that the bot needs to be able to store user and guild variables, as I described in the post, so that's what I'm trying to do, and make it work with "events", where I will be adding the code for new events as needed, so that others could then branch-chain "events" together to create a possible sequence of actions (they'll be doing this through a gui of sorts)
Do you mean like custom commands
How come this doesnt work, the error I keep getting is: ImportError: cannot import name 'Intents' from 'discord' (unknown location)
import os
import discord
from discord import Intents
from discord.ext import commands
intents = Intents.default()
intents.message_content = True
# Create a bot instance with a command prefix
bot = commands.Bot(command_prefix='!', intents=intents)
# Event: Bot is ready
@bot.event
async def on_ready():
print(f'Logged in as {bot.user.name} ({bot.user.id})')
# Command: Ping
@bot.command(name='ping')
async def ping(ctx):
await ctx.send('Pong!')
# Run the bot with the token
bot.run("")
If that's what I think about, you can just make sort of custom commands language and parse it
Lib conflict / installation problem. Do you use venv?
All I have installed is discord.py
Did you install it in venv
Nope, I installed it in visual studio terminal
Virtual environments are isolated Python environments, which make it easier to keep your system clean and manage dependencies. By default, when activated, only libraries and scripts installed in the virtual environment are accessible, preventing cross-project dependency conflicts, and allowing easy isolation of requirements.
To create a new virtual environment, you can use the standard library venv module: python3 -m venv .venv (replace python3 with python or py on Windows)
Then, to activate the new virtual environment:
Windows (PowerShell): .venv\Scripts\Activate.ps1
or (Command Prompt): .venv\Scripts\activate.bat
MacOS / Linux (Bash): source .venv/bin/activate
Packages can then be installed to the virtual environment using pip, as normal.
For more information, take a read of the documentation. If you run code through your editor, check its documentation on how to make it use your virtual environment. For example, see the VSCode or PyCharm docs.
Tools such as poetry and pipenv can manage the creation of virtual environments as well as project dependencies, making packaging and installing your project easier.
Note: When using PowerShell in Windows, you may need to change the execution policy first. This is only required once per user:
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
So I should install this instead?
They don't create custom commands, but they do need to be able to chain pre-created custom commands, which I will be adding as necessary, which will be using user/guild variables
You only need the note and how to create venv. To activate it, ctrl + shift + p -> Python: Select Interpreter and select the venv inside your current project. After that, make sure to create new terminal and do pip install discord.py @restive mantle
Just make custom language and parse it
How is that? O.o
And what about storing the variables?
Which of these should I choose?
You can do smth like
COMMAND ban_and_log
BAN(id: {args[0]}, reason: {args[1:]})
SEND({settings.LOG_CHANNEL}, "Banned stupid <@{args[0]}> for {args[1]}")
Might be a bad design of language but it's up to you how to do that
Just don't use exec when parsing ☺️
Read the embed first, you clearly never created venv
Also install python from official python site, ms store version is broken af
That thing is pretty scalable, can make UI command blocks like in scratch that will convert to your code; to add a new feature you just update parser, and so on and so on
Data storage comes to just a bunch of text
@fading yew
Could I get a link to an article/blog explaining this approach? I don't quite get what exactly this gives me. I'd still need to map this custom language to python code and integrate it with the library, right? What exactly does it give me? I'm a bit confused on how this'll be helpful, maybe I'm looking at it from the wrong angle
I just made this approach up-
It gives you the extensibility
I have now installed venv, And now I have plenty of new things in my explorer. Where would I add my main.py script?
Thanks for the help also🤍
And how can you do something without python code?
You created a venv inside venv
Who would be using this custom language again? 😅 I was thinking I'd do smth more like: a searchable drop-down menu with possible pre-defined "actions/events/commands", when chosen, additional options may appear, and the ability to chain this to another one. But this is about the gui. I'm just thinking about how to store the stuff. I wouldn't be storing the python code, that would just be.. well, part of the bot. The events table would hold the unique name of one of these "actions" from which one can choose from a drop-down, which would be the key in a python dictionary, containing the function to be executed with the other stored parameters from the events table, pulling variables if needed from the value table. After creating such a chain of events, it would be executed.
How does this custom language help me store stuff? I don't get it 
I accidentally uninstalled all my folders
but now everything is restored ☺️
The custom language serialises those actions
So you now have a project root and venv folder inside right?
Well is a project root a main folder? Because I have a folder named commission bot, and inside there I have venv.
how can i get user id from username
Show your current file hierarchy
In what context
It's kinda weird tho, because I watched some yt tutorials. And they don't use venv and still get it to work.
Seems alright. Create python scripts in root dir, not in venv
Cause they stoopid
I see
Now do ctrl + shift + p -> Python: Select Interpreter
And what is a root dir
ok
The dir where your venv is
Can also collapse the venv since you don't need its contents
So like this then?
It is possible ofc, but just install both discord.py and pycord globally and not a single project will run. Venvs are for isolating dependencies
I have no idea what "open editors" is but the hierarchy is ok
Did this?
Open editors is just what scripts I have open
You don't use visual studio?
I have it, but my open scripts display as tabs
Great, now open new terminal and install dpy
Make sure there's (venv) at the beginning of prompt
Should I uptade?
You can but that's optional
member = await guild.fetch_member(username='msii9')
return member.id
how can i get user id from username because fetch_member only takes id
guild.get_member_named("username").id
@vale wing It's working now man!! Thanks for the massive help. 🫶
discord.ext.ipcx Error in join_channel: 'NoneType' object has no attribute 'id'
member = await guild.get_member_named('msii9').id
return member ```
First, it's not a coroutine hence you don't need to await it
Second, is members intent on
👍
What's the object type called if someone tags a channel?
I have a command that's meant to take a channel ID, I never in my life expected someone to just @ a channel lol
I am way too large 🙄
!d discord.abc.GuildChannel
class discord.abc.GuildChannel```
An ABC that details the common operations on a Discord guild channel.
The following implement this ABC...
thats every channel
but you can only accept for example text channels only
then its
!d discord.TextChannel
class discord.TextChannel```
Represents a Discord guild text channel.
x == y Checks if two channels are equal.
x != y Checks if two channels are not equal.
hash(x) Returns the channel’s hash.
str(x) Returns the channel’s name.
so do I just do "If type(input) == "TextChannel" i'll detect if someone has @'d a channel instead of using a channel ID?
you can use built in converters
instead of checking for correct type manually
A hands-on guide to Discord.py
this is an example with prefixed command but if you are using slash commands then its https://fallendeity.github.io/discord.py-masterclass/slash-commands/#slash-command-parameters
A hands-on guide to Discord.py
How can I create these boxes? Instaed of the bot sending just a normal message?
Or what's the name of these boxes
its called an embed
Those are called embeds
ooo thanks
👍
Ty @slate swan 😄
This change is much better
now I dont have to rely on people doing the command right.

While im here. How do I make a command sleep for a second?
Someone mentioned it once before
like many days ago
!d asyncio.sleep
coroutine asyncio.sleep(delay, result=None)```
Block for *delay* seconds.
If *result* is provided, it is returned to the caller when the coroutine completes.
`sleep()` always suspends the current task, allowing other tasks to run.
Setting the delay to 0 provides an optimized path to allow other tasks to run. This can be used by long-running functions to avoid blocking the event loop for the full duration of the function call.
Example of coroutine displaying the current date every second for 5 seconds:
well i have my bot bot with not many commands and i thought to create more commands but i need ideas if you have something that can be challenging and fun after pls reply
Discord mod simulator! Very challenging to make, bobux bot dev team can't complete this for 6 months!
what is this?
what are the functions?
Sorry it was a local meme
ok
Tbh I already spent all my ideas on bobux bot so can't really help
ok
Make a tag system😋
how could i get an emoji object out of message content
end goal is to get the link for the emoji someone sends
You'd have the extract the emoji IDs from the content yourself
With re or something similar
gross, regex
alright, thanks. wasnt sure if there was an easier way i wasnt aware of
tag system?
anyone know a good low cost db that i can use for my bot?
like sqlite?
@bot.event
async def on_message(message):
if message.mentions:
for member in message.mentions:
if member.status == discord.Status.offline:
await message.channel.send(f'{member.name} is currently offline.')
break
i tried to code a bot that when someone being mentioned but offline, the bot gonna notify that they are offline, but when i test the bot, anyone i mention, both online and offline, triggered the bot, anyway to fix this?
anyone have a problem with hybrid commands only working via slash command and not working via text command?
you can do hybrid commands and slash commands on one bot, correct?
Yes
yea everything slash is working but its not triggering if i use the prefix
which is the opposite of what i thought would happen when changing this from prefix only command to hybrid
Are you sure you have the right intents?
all intents
Processing commands?
wym
Are you overriding the on_message event? If so, you'd need to call the process command method
I have no more idea after this 🫠
i have an on_message event in a seperate cog
Maybe check your bot's permissions to view the channel that you're running the command?
this bot has basically admin permissions
how do i do this? call the process command method disregard, i got it
the hybrid command works flawlessly on one bot, but only the slash command works on the other bot. same cog for both. both have all intents. both bots have the same permissions. 
oh theres an on_message in the main file.. thats gotta be it
So... how do embed videos work? looking at the docs and saw that was added. do I just input parameters of the url, height and width and it'll implement it into the embed?
or is it something I can't set and just use image/thumbnail for that data?
What have you tried so far?
@bot.event
async def on_message(message):
if message.mentions:
for member in message.mentions:
if member.status == discord.Status.offline:
await message.channel.send(f'{member.name} is currently offline.')
break
i tried to code a bot that when someone being mentioned but offline, the bot gonna notify that they are offline, but when i test the bot, anyone i mention, both online and offline, triggered the bot, anyway to fix this?
class MyBot(commands.Bot):
async def on_member_join(self, member):
role = discord.utils.get(member.guild.roles, id=role_id)
await member.add_roles(role)
this on_member_join isnt asigning role on member join whats wront with it
@commands.Cog.listener()
async def on_message_delete(self, message):
log_channel_id = await get_deleted_messages(server_id=message.guild.id, db_connection=self.bot.db_connection)
if log_channel_id:
log_channel = self.bot.get_channel(log_channel_id)
if message.content:
log_embed = discord.Embed(
title="Message Deleted",
description=f"Message in {message.channel.mention} deleted.",
timestamp=discord.utils.utcnow(),
color=config.main_color
)
log_embed.add_field(name="Content", value=f"``{message.content}``", inline=False)
log_embed.set_footer(text=config.footer_text, icon_url=self.bot.user.avatar.url)
log_embed.set_author(name=message.author.display_name, icon_url=message.author.avatar)
log_embed.set_thumbnail(url=message.author.avatar)
await log_channel.send(embed=log_embed)```
How could I make this ignore bulk deletions? basically purges. Because if another bot purges, its gonna want to log all of those, it would probably spam the hell out of my bot too
Or how I can do a special embed for Bulk messages/purged messages.
how to get user icon
;-; it annoys me this isnt a thing
!d discord.User.avatar
property avatar```
Returns an [`Asset`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Asset) for the avatar the user has.
If the user has not uploaded a global avatar, `None` is returned. If you want the avatar that a user has displayed, consider [`display_avatar`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User.display_avatar).
You'd have to listen to the on_audit_log_entry_create, check if the action is message deletion, then check if the amount of messages deleted is greater than 2
I didnt either
\o/
thats why I was shocked lol
is using dict effective in discord coding.?
that doesn't have anything to do with discord, but dictionaries are pretty good with data lookup speed, it's good for any program you're writing on given a need for it
@bot.event
async def on_message(message):
async with aiosqlite.connect("Opdb.db") as db:
async with db.cursor() as c:
# COLLECTING DATA
await c.execute("SELECT * FROM status WHERE id = ? ", (message.author.id,))
ID = await c.fetchone()
await c.execute("SELECT * FROM enemy WHERE id = ?", (message.author.id,))
enemy = await c.fetchone()
await c.execute("SELECT * FROM points WHERE id = ?", (message.author.id,))
p = await c.fetchone()
# CHECKING IF DATA EXISTS AND IF NOT CREATING DATA
if not ID:
await c.execute("INSERT INTO status (id, Name, Level, Fruit, hp, health, damage, xp, xpr, levelr, style) VALUES (?,?,?,?,?,?,?,?,?,?,?)", (message.author.id, "NULL", 0, "None", 10, 10, 1, 0, 5, 15, "Fist"))
if not enemy:
await c.execute("INSERT INTO enemy (id, en, eh, ehr, es, el) VALUES(?,?,?,?,?,?)",(message.author.id, 'Snake', 5, 5, 0.5, 0))
if not p:
await c.execute("INSERT INTO points (id, p, hp, dmg) VALUES(?,?,?,?)",(message.author.id, 3, 1, 1))
# FINISH COLLECTING OR CREATING DATA
await db.commit()
await bot.process_commands(message)
No error received, doesn't do anything tho not sure why
does message.authoer.id and ctx.author.id not give the same value.?
hey guys I'm working on my first discord bot and it says it's online and it says it's connected and stuff but it wont reply when I do my command, here's my code (removing the token):
#TOKEN: token
import discord
from discord.ext import commands
intents = discord.Intents.default()
intents.messages = True
bot = commands.Bot(command_prefix=';', intents=intents)
@bot.event
async def on_ready():
print(f'Logged in as {bot.user.name} ({bot.user.id})')
# Get the channel where you want the bot to send a message
channel_id = 1198210346314387456 # Replace with the actual channel ID
channel = bot.get_channel(channel_id)
# Check if the channel is valid
if channel:
await channel.send('Hello, I am your bot! I am now online.')
else:
print(f"Error: Channel with ID {channel_id} not found.")
@bot.command(name='hello')
async def hello(ctx):
global channel
print("Command Received")
await channel.send('Hello, I am your bot!')
bot.run('token')
also I've discovered that it can't read messages for some reason
I've used the simple script provided my all tutorials to try and host a discord bot, but why can't i get the link to the created web server? it was working fine two months ago, so idk why it suddenly only shows the server as "/"
I fixed my problem
How to get invites n stuff like that, on member join. So when someone joins, we wanna know Invite link, and Invite Link Creator, how can we do that?
@commands.Cog.listener()
async def on_member_join(self, member):
log_channel_id = await get_member_joins(server_id=member.guild.id, db_connection=self.bot.db_connection)
if log_channel_id:
log_channel = self.bot.get_channel(log_channel_id)
if log_channel:
log_embed = discord.Embed(
title="Member Joined",
description=f"{member.mention} has joined the server.",
timestamp=discord.utils.utcnow(),
color=config.main_color
)
log_embed.add_field(name="User ID", value=member.id, inline=False)
log_embed.add_field(name="Account Created",
value=f"{discord.utils.format_dt(member.created_at, style='R')} / {discord.utils.format_dt(member.created_at, style='f')}",
inline=False)
log_embed.add_field(name="Server Joined",
value=f"{discord.utils.format_dt(member.joined_at, style='R')} / {discord.utils.format_dt(member.joined_at, style='f')}",
inline=False)
await log_channel.send(embed=log_embed)
invite code actually
or link whatever
Yeah ^
Is there a way to send emails with the bot with some other library?
!d email
Source code: Lib/email/__init__.py
The email package is a library for managing email messages. It is specifically not designed to do any sending of email messages to SMTP (RFC 2821), NNTP, or other servers; those are functions of modules such as smtplib and nntplib. The email package attempts to be as RFC-compliant as possible, supporting RFC 5322 and RFC 6532, as well as such MIME-related RFCs as RFC 2045, RFC 2046, RFC 2047, RFC 2183, and RFC 2231.
The overall structure of the email package can be divided into three major components, plus a fourth component that controls the behavior of the other components.
👌
...
Have you even tried debugging it on your own
e.g. adding print statements to understand the actual flow of your code and where it goes/doesn't go - and what the results of the queries are
Because just sending "..." after like 7 hours or something of not doing anything, not even trying, is pretty much useless
i fell asleep
been working on this all night
But why does message.author.id return a different value from ctx.author.id. Ive been searching for answers but i dont get anything
Is there a channel to help people with a code file for a discord bot?
here manz
Oh cool, thank you.
It doesn't
!d discord.Message.author




