#discord-bots
1 messages · Page 371 of 1
oh I see why, the choices are value of type int while the game type is str
what do you mean?
I mean the choices values are int while the game argument is str
so you giving a int instead of a str, change the game typehint to int
and shall all be fixed
huh and accessing name? that is not a thing I believe
everything is working now but i get this Command 'host' raised an exception: AttributeError: 'int' object has no attribute 'name'
yes because game is a number and not a Choice object
if you want the game name maybe map them into a dict
I'm sort of confused on what you are saying but i will say what i am trying to do with this slash command
I am trying to making it so when someone click on one of those choices and enters it the bot will give a different response for each option
I am unsure either of how to explain this to a newbie.
what you have to do is create a dict object and put every number as a key and the value as the game name,
here an example of using a dict but that's too complex to a newbie
games = {
1: "Mag Game",
2: "Lob Game",
3: "Game Night"
}
game = int(input("enter a game: "))
print("the game you entered is", games.get(game, "Mag Game"))
what a newbie will originally do is:
if game == 1:
print("the game you entered is Mag Game")
elif game == 2:
print("the game you entered is Lob Game")
elif game == 3:
print("the game you entered is Game Night")
exam the first code sample, and learn and understand how dict.get works and how to use dicts
I see, but how does that implament to a discord bot that just looks like prints..
I am showing how you must deal with them not implementing them directly to your code as it seems like spoonfeeding, you should take those and figure how to use them
Traceback (most recent call last):
File "main.py", line 14, in <module>
from pymongo.mongo_client import MongoClient
File "/home/runner/xeph-hunchothreat/.pythonlibs/lib/python3.8/site-packages/pymongo/__init__.py", line 90, in <module>
from pymongo.collection import ReturnDocument
File "/home/runner/xeph-hunchothreat/.pythonlibs/lib/python3.8/site-packages/pymongo/collection.py", line 40, in <module>
from bson.raw_bson import RawBSONDocument
File "/home/runner/xeph-hunchothreat/.pythonlibs/lib/python3.8/site-packages/bson/raw_bson.py", line 57, in <module>
from bson import _get_object_size, _raw_to_dict
ImportError: cannot import name '_get_object_size' from 'bson' (/home/runner/xeph-hunchothreat/.pythonlibs/lib/python3.8/site-packages/bson/__init__.py)
``` in my discord bot. i really dont know what is wrong.
you may want to share some code
well okay thank you for your time
sorry i just fixed it. just had to uninstall pymongo and reinstall it
seems about right, you get the permissions on the second screen once you've selected a server
those two are your oauth scopes, bot and applications.commands
i cant recall what it looked like in the early days, but afaik every bot invite link shows the same two screens, oauth scopes first, then bot permissions
(if the oauth link doesn't include the bot scope, then you won't see the second screen)
whats actually freaky is if the first screen shows "Join servers for you" 🥴
you forgot the pip part of the command
can you run py -0 in the terminal
cool, so do py -m pip install discord.py
so instead of pip i have to do py -m pip?
and btw it worked
yes, the reason is that you didn't add python to the path apparently
!intents
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.
did you read the embed?
can we get on a call and i can screenshare because theres a other mistake
no sorry. i don't do calls, open a help thread.
alright then this is what is happening
oh wait i think ik the problem
your token is visible there btw
its okay
its whatever
i will just reset it and i fixed it btw
thanks for all the help
Yo i have a question about cogs
when i write a cog in a different file, for example: mycog.py
How can i import it to the main file so i can use it
await load_extension(name, *, package=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Loads an extension.
An extension is a python module that contains commands, cogs, or listeners.
An extension must have a global function, `setup` defined as the entry point on what to do when the extension is loaded. This entry point must have a single argument, the `bot`.
Changed in version 2.0: This method is now a [coroutine](https://docs.python.org/3/glossary.html#term-coroutine).
basically u with ur bot u would do await bot.load_extension("cogs.mycog")
What about await bot.add_cog(“…”)
whats the difference between the 2?
or do i need load extension to be able to use add cog?
that goes inside ur cog
async def setup(bot):
await bot.add_cog(MyCog(bot))
adding ur cogs as an extension has an added benefit of being able to use the library methods to unload and reload cogs/extensions
Is there a channel where I can get ideas for my bot?
You don't have to do that tho
You could just auto load the cogs instead of manually loading them

its easier for beginners to understand adding cogs manually
But then they think thats the only way ya know, so its better if you just teach them the auto loading imo
Also that's just an example
Also also, you don't "load' a cog
You load the extension which calls a function called setup which is where most people add a cog to the passed bot
ty
i have another question.. i noticed people using this:
async def setup_hook():
for file in os.listdir("cogs"):
if file.endswith(".py"):
await bot.load_extension(f"cogs.{file[:-3]}")```
cant we just do: @bot.event async def on_ready(): await bot.load_extension("cogs.cog") print('Cog loaded') to auto load the cog?
thats what he meant by auto loading yeah
it goes over the cogs folder and adds each cog
also try not use on_ready for this use the setup_hook
why? whats the difference?
on_ready is called multiple times thoroughout a bots lifetime setup_hook is called only once
oh so i will load the extention multiple times if i use onready
yeah
the code would be called multiple times in an unpredictable manner due to resuming gateway connections to discord
can this become simpler like: @bot.event async def setup_hook(): await bot.load_extension("cogs.cog")
it would load only 1 particular cog if u have multiple cogs u would need to use a for loop
u can use multiple cogs
is that common practice tho?
yep
usually u group similar commands under a cog
u can have several categories of commands
ok thanks
nerd or what 😭
More like common misinformation
People should know how it works instead of copypasting some code and thinking it works like magic
ur like magic
<3
Also setup_hook isn't an event
@merry cliff one more question
so i've made a tickets command with a button that creates said ticket. it works fine, though the button doesn't work after restarting the button. is there an easy way to keep the button functional even after restart?
ill check this out, thanks!
I need a Programmer [discord.py]
if you need a simple-ish bot i could help but i'm not really that advanced yet :p hmu and tell me what features you need
i need to create a bot
i have 4 Programmers now so we need to create a games bot
Why do u need so many devs for a game bot
ye na im too inexperienced soz
That is also a thing which might apply here idk
chatgpt thinks that 3 isn't a prime number. It's more stupid than a toddler but confident in its stupidity
i love how it sometimes writes code incorrectly, i point it out and folks blame me for it
like cmon man
yet it cooked up rn
keyword sometimes
hell yeah
async def stats(interaction: discord.Interaction, ctx):
stats_count = ctx.guild.member_count
em = discord.Embed(description=f'`Current Member Count`: {stats_count}')
await interaction.response.send_message(embed=em)```
Error: parameter 'ctx' is missing a type annotation in callback 'stats'
then how would i get the guild member count?
use interaction.guild instead
np
my problem is im trying to make a log tracker(counts the number as i use the command) I can't get it to update the number in my Data.json file
does assigiing it to data also update the file?
consider using a db like sqlite
you need to rewrite the whole json for that to work which can and will corrupt the file at some point
is there a way i can make the tracker without having to do all that?
im just confused on how to get it to udpate the number after I use the command, like why doesn't the
log_number = int(data["Log_Number"]) log_number += 1
work?
it sends the message with the Log number, but doesnt update the number to 2
Because data is just the data inside memory. If you want to update it in the database you will need to update it.
do some basic research lol
like https://realpython.com/python-json/
bruh wht is worng with the server icon

?
u could yes, will we help u with that? no
May want to read their terms of service
why not?
read their tos
i mean for educational purposes since i'm tryna learn
then u should pick a better site which allows such automation
such as?
what matter is method not the site, and then you can try it on your own risk
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.
paste ur code and send the complete traceback
nah fr im tryna learn im not for the memes 😭
mann how tf do slash commands work
intents = discord.Intents.all()
intents.members = True
bot = commands.Bot(command_prefix=commands.when_mentioned_or("."), intents=intents)
client = discord.Client(intents=intents)
tree = discord.app_commands.CommandTree(client)
@client.event
async def on_ready():
await tree.sync(guild=discord.Object(id=1247794415582318652))
print('ready')
shi does NOT print 'ready'
By typing / and choosing the command you want to execute
folks i know how to use a slash command ion kno how to make one
are u doing bot.run ?
The intent name for message content is message_content, not messages
yh this the actual command
@tree.command(name="name", description="description")
async def slash_command(interaction:discord.Interaction):
await interaction.response.send_message("command")
``` but the print('ready') doesn't even work soo
ok i change my question how did u learn it without someone telling u "tos"
intents.message_content = True
Line 6, rename messages to message_content if you want your command to work
messages is included in Intents.default()
are u doing bot.run or client.run?
im doin bot.run cs all my other commands use a prefix, do i do both orrr
but i understand what you mean tho
i ain runnin the client
u dont need both bot and client
could someone please explain quickly what cogs are?
u can just use it like
@bot.tree.command()
whats that?
ohhh
bot comes with a tree out of the box
ima try rq
same with @bot.event
i still need
tree = discord.app_commands.CommandTree(bot)
``` right
is asking wht cogs are is against tos too?
@rain hedge
( i have no clue too )
folks yo profile looks cool ash
thanks
profiles*
np
nah im talmbout yours fr
oh thx
whats good about it
i never expected this compliment
it might be against tos to compliment my pfp
😭
@shrewd apex
bot = commands.Bot(command_prefix=commands.when_mentioned_or("."), intents=intents)
tree = discord.app_commands.CommandTree(bot)
@bot.tree.command(name="name", description="description")
async def slash_command(interaction:discord.Interaction):
await interaction.response.send_message("command")
@bot.event
async def on_ready():
print(f'{bot.user} successfully logged in!')
await tree.sync(guild=discord.Object(id=1247794415582318652))
```discord.errors.ClientException: This client already has an associated command tree.
explain im dumb man terms
nah fr mentioning tos is crazy 💀
its literallt like halmet u can kill with it but u shouldnt stop teaching ppl how to use halmet bc he might kill someone
see how you're using bot.tree? That's the tree that is already associated to your command.
You're creating a second tree, named tree, and a client cannot have two trees.
so i dont need to define tree = discord.app_commands.CommandTree(bot)?
Nope
no
i can't do await tree.sync(guild=discord.Object(id=1247794415582318652)) then right
i'm genuinely lost with the tree n slash commands icl i'm too slow 😭
yert
can yall tell me why this pops up when i don't even have such a command in my code 😭
No because your tree is "bot.tree" not "tree"
Using views -> https://fallendeity.github.io/discord.py-masterclass/views/
A hands-on guide to Discord.py
# after disabling all components we need to edit the message with the new view
# now when editing the message there are two scenarios:
# 1. the view was never interacted with i.e in case of plain timeout here message attribute will come in handy
# 2. the view was interacted with and the interaction was processed and we have the latest interaction stored in the interaction attribute
async def _edit(self, **kwargs: typing.Any) -> None:
if self.interaction is None and self.message is not None:
# if the view was never interacted with and the message attribute is not None, edit the message
await self.message.edit(**kwargs)
elif self.interaction is not None:
try:
# if not already responded to, respond to the interaction
await self.interaction.response.edit_message(**kwargs)
except discord.InteractionResponded:
# if already responded to, edit the response
await self.interaction.edit_original_response(**kwargs)
Disable all just disables all components in the view, stop, stops the view and confirm is a variable to let the view know it's confirmed, just a var.
This is the _edit function await self._edit(view=self) self gets passed, self is the current class. This just edits the view when it gets changed.
There are enough comments to get you started and I recommend running the code yourself and change things and look into it.
Yes and no, you want to disable the view before stopping because otherwise the user could still click the buttons but the app won't respond. And you want to stop the view because otherwise it would use too much resources at some point.
In this specific case the confirm is true, so buttons get disabled, edit pushes the disabled to Discord and then the view gets stopped. That gets returned to the command function and then you could do further logic.
Ah a paginator, then you'd edit the View to show the new text. I might've an example..
Our old and trusty @hushed galleon has made a good View for this @slate swan -> https://github.com/thegamecracks/thegamebot/blob/v2/bot/utils/paging.py
!pypi discord-ext-pager is the lib you can install for it
A view-based paginator library for discord.py 2.0
Released on <t:1699903151:D>.
verinoice
A discord.py 2.0 paginator library with a similar interface to discord-ext-menus. - thegamecracks/discord-ext-pager
Nice, yeah I grabbed the one we talked about some time ago.
"some time ago" #discord-bots message
lmao
Just made me feel old 
If you have an issue regarding the community go to #community-meta
!pate
!paste
https://paste.pythondiscord.com/P4FA
Anyone know why the logging on this wont work, ive tried adding & removing logging statements, ive also tried another bot with this code and it didnt work so ik its the code, although i use this exact code with different channel ids on a different bot, and ik its not a perm problem since bot has admin + all intents
is there any way I can write this code to run faster?
I feel like having 3 for loops within a for loop might run slowly
It's generally never a good idea to agonize over "might"
Run the thing and profile it if you're worried
Cant you put that logic into SQL query?
Anyone here have experience with integrating their bot with a Plex Server?
Going from 3 comprehensions to 1 loop would be faster but it's still O(n). It won't be noticeable
@client.event
async def on_connect():
print("Huncho is Online")
print(f"{len(client.guilds)} Servers. {len(client.users)} Users.")
await status()
try:
await client.add_cog(AntiChannel(client))
print("AntiChannel Cog Loaded")
except Exception as e:
print(e)
i cant tell if my cog wont load or this wont work.
class AntiChannel(commands.Cog):
def __init__(self, client):
self.client = client
db = mydatabase["hunchodb"]
@commands.Cog.listener()
async def on_guild_channel_create(self, channel):
whitelisted = db.find_one({"_id": channel.guild.id})["whitelisted"]
async for i in channel.guild.audit_logs(limit=1, after=datetime.datetime.now() - datetime.timedelta(minutes = 2), action=discord.AuditLogAction.channel_create):
if i.user.id in whitelisted:
return
anti = db.find_one({"_id": channel.guild.id})['antinuke']
if anti is False:
return
await channel.guild.ban(i.user, reason="Anti-Nuke: Creating Channels")
await i.target.delete(reason="Anti-Nuke: Deleting user created channels")
logs = db.find_one({"_id":channel.guild.id})["logschannel"]
c = self.client.get_channel(logs)
embed = discord.Embed(title="Anti-Nuke", description=f"{i.user} has created a channel, and has been banned by Anti-Nuke", color=0x2f3136)
await c.send(embed=embed)
``` help pls
You should not be using on_connect for one time setup things. It runs several times and effectively randomly
Also if you don't want someone creating channels, why do they have the permission to do that in the first place?
I can subclass Context and use CustomContext in prefix commands, is there anything similar I can do for interactions? bcs custom context requires get_context for prefix commands but idk if there's something similar for interactions
There's no library support for custom Interactions, because Interactions are a type published by discord with a defined structure
anti-nuke
You could just not let them have those perms
some ppl aint that smart 🤷
Thank you
If they're too stupid for that, what makes you think they're smart enough to not give someone rank to kick your bot first?
why you put the bot above those roles. trust everything in my bot is very easy to setup.
you get a message that says it only works if it is above the member.
trust i know my setup works. i just need help with the function itself.
yo, I wanna add a buy item feature, but since each server has a unique shop, is there a way to create a drop down menu of items in a shop from accessing the database?
Idk fam, you could just have people use the systems that already exist and are far more reliable than your bot
Every couple of days I hear someone crying about an anti-nuke bot that got compromised or didn't work because they're inherently flawed
okay so are you gonna help or not, i didnt ask for your opinion?
lol my help is to use the systems that actually work instead of this hacky stuff, your call if you don't want that help
so if you weren't gonna help with wt i sent then why say anything to me ?
That is the help. You just don't want it
and i wanted to make my own anti-nuke is there a problem with that?
There is, because as said before it is flawed
and exactly why i asked for help? r u not using your brain?
okay the concept is for me to deal with? not you?
I'm telling you how to actually prevent things from happening in a guild. If you don't accept that, your goal isn't actually to keep people safe but to double down on this naive implementation
okay and how does that help me with my code at all whatsoever?
By helping with the core goal, which is to prevent these things from happening
but is that wt i asked for?
Are you familiar with the XY problem?
is that wt i asked for tho ?
Are you familiar with the XY problem?
completely dodged my question then wanted me to answer yours?
It is related to your question
Good help seeks to understand what your core goal is and helps you with that, rather than blindly helping with the (flawed) proposed solution you already have
If your goal is not to prevent these things from happening, then my help doesn't apply
And yeah, you can populate a select however you want before you send it, noting that there's a maximum of 25 options per select
how do I do that?
You can subclass Select then pass the options you want into the super constructor
Also implement callback
Im still a lil confused, is there any documentation or examples I can see?
Are you familiar with how to subclass?
is that class inheriting from another class?
Yes exactly
what does super constructor and callback mean
You can make your own class inheriting from Select. You will want to two things in it:
-
override
__init__. In this you will call thesuper().__init__(). You can pass whatever you want like you would to a normal select, including options= -
override callback(self, interaction). This does whatever you want when the select gets interacted with
how do you inherit from select?
How do you inherit from any class?
wait, which class do I inherit from?
discord.ui.Select
does ui select affect slash commands?
I thought it was for like buttons or something
yea yea those
I think thats why I was a lil confused lol
!d discord.app_commands.autocomplete
@discord.app_commands.autocomplete(**parameters)```
Associates the given parameters with the given autocomplete callback.
Autocomplete is only supported on types that have [`str`](https://docs.python.org/3/library/stdtypes.html#str), [`int`](https://docs.python.org/3/library/functions.html#int), or [`float`](https://docs.python.org/3/library/functions.html#float) values.
[`Checks`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.check) are supported, however they must be attached to the autocomplete callback in order to work. Checks attached to the command are ignored when invoking the autocomplete callback.
For more information, see the [`Command.autocomplete()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.Command.autocomplete) documentation.
Warning
The choices returned from this coroutine are suggestions. The user may ignore them and input their own value...
I was reading the docs and it said that it was a list of suggestions instead of something compulsory, should I just return an error message or something if they type something that isnt in the database?
Yeah your options are to either do validation in a command, or to present them with a Select
alright
You shouldn't be using interaction.message.edit, you can just respond with interaction.response.edit_message
I want the bot to edit the message
and that's what interaction.response.edit_message does
its still not working @fast osprey
code? error?
You have if statements. Have you done any debugging to see how those are behaving?
you use discord.py?
I asked many people for help but no one knows the answer 
ye
then do it?
yeah do some debugging
if the if statement doesn't pass, nothing happens in the callback
I'm sorry but I'm not very good at programming and I don't even know what you're talking about
You can just put print statements in your code to see what's happening
# If this evaluates to true, run code
if interaction.user.id == self.user_id:
embed = interaction.message.embeds[0]
embed.description = embed.description.replace("None", interaction.user.mention)
await interaction.response.edit_message(embed=embed)
await interaction.response.defer()
# Else, do nothing
Do you want to edit the original message by pressing the buttons?
You don't understand print statements?
yes
I want the user who clicks the "Send" button was added to an earlier message
I want the bot to edit it
try using this method. (I don't use discord.py but this is what it says in the documentation)
You don't want that method
when someone clicks sending
bot will edit sending litecoin and instead of none his nickname will appear
so what should I do
You should debug to see what your callbacks are doing
python debugging?
or just print statements
how to do print statements
you print()
Can you add these print statements to code
and what will it give me?
no I don't spoonfeed
adding print statements inside your if conditions will help u see what condition is being reached and what isnt
but how should I add it and where?
Wherever in your code you want to see what's happening
by using the combination of p r i n t ( ) keys on ur keyboard
Have you already used the methods I have taught you?
they told me not to use them
I use them to edit my messages and they work, try it.
What specifically does it fail?
Does anyone know what the kwargs for discord.utils.get() specifically for guild.text_channels?
does it use the attributes that discord.TextChannel uses?
You haven't printed anything in your callbacks. You have no idea what's going on in there
yes
Yo
How do people make select menus/drop down menus, show options you have already selected when you load the menu again
Yes its from a db, but how to do it in dpy.
I know its like a very stupid question and prolly simple, just wanna know how to do it tho lol.
well, the idea would be to get the data that you need, turn that data into options, and add them to the select
But it shows selected already..?
oh you mean how that appears? presumably default=True on one of the options
I guess..?
huh, i didnt know default worked for multiple options, guess that makes sense
So its just default?
yeah, looks like it
oh wait a minute, i think i can replace my /inbox staff add|list|remove commands with a MentionableSelect...
o, i need dpy latest to get default_values...
first time using mentionable select but it turned out well
https://github.com/thegamecracks/theticketbot/commit/ef32227324d2db48c2665a8744501ad4a5d203ba
Holy crap is that a ticket thread
I think it was a ticket thread
hi leonardo!
Hi. what the FUCK is this chat
Guess what this guy is saying 😁
idk man it's like 3am for them why would they reply lmao
OK, are the videos necessary here?
You'll probably get banned for spam before they wake up
Yes
Im just going along with it cuz I think its funny lol
Just a lil fun, no harm done tbh
Plus they have a funny voice
Huh?
yeah it sounds like my dogs chew toy
What you be doing with your dogs chew toy..?
Alr ill see yall later cuz imma get banned prolly for just some fun :/
plz dont ban me
Vencord banned me within like 3 seconds cuz I was asking for help one time 
That was a good day
Fr 😭
As a reminder, we need to remain on topic. Keep in mind whether your videos are disruptive or not.
If you would like a place to be silly (although please don't meme dump) we have the OT channels.
Alright, im sorry blud. Ill leave chat now. Love you!
Thanks Daiyailaly
ur a w
Fr you a W
I'm actually struggling to play the videos so there's not much I can do anyway.
@craggy notch needs to be promoted
They aren't bad lol
They are just him talking in a nerd voice tbh
I downloaded one, and yeah, it's fine.
It's just off-topic here. This is a topical channel for people to discuss and get help with developing Discord applications/bots.
Yeah we were just bored, sorry tbh.
sorry!
We truly sorry lol. We were honestly just bored n wanted something to do, we prolly won't do it again, if we do just mute us for like 3 weeks or something lol.
I am new and I making a discord bot and I have completed the main.py and I have yet to add the cmd but I don't know how it is done and I went to another website and copied and pasted the code but still it is not working, maybe that code It is not connecting to my bot
!paste your code with any tokens removed and we can look at it
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.
if your command isnt running, maybe you're missing the message content intent?
It would print in your console ^
What's the command grouping thing called again?
nvm found it. :D
from discord.ext.commands import Cog, Bot
import discord
from discord import app_commands
from discord import Interaction
from discord.app_commands import guild_only, command
class TestClass(Cog):
def __init__(self, bot:Bot, config:dict):
print("[Cog] TestClass has been initiated")
self.botBot = bot
self.config = config
poll = app_commands.Group(name='poll', description='polls for polls and polling')
@poll.command(name='create', description='Create a poll')
async def create(self, interaction: discord.Interaction, question:str, option_one:str, option_two:str):
await interaction.response.send_message("Results go here.", ephemeral=True)
@poll.command(name='info', description='Info on a poll')
async def info(self, interaction: discord.Interaction, poll_id:int):
await interaction.response.send_message("Results go here.", ephemeral=True)
``` found my example file that had it :D
if you want all the commands of a cog to be in the group, use a GroupCog
class UwUAnimeCog(commands.GroupCog, name="group_name")
@commands.command(...)
...```
Does this basically work the same way?
yes
https://paste.pythondiscord.com/VTOQ
why buttons there is not working?
bot doesnt responding to butttons
line 83, 98, 93
- async def reset(self, button: discord.ui.Button, interaction: discord.Interaction):
+ async def reset(self, interaction: discord.Interaction, button: discord.ui.Button):
its ordered wrong
i got one error
!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.
oh check ur on_message u have a try block but no except
try:
... # code here
except: # <-- u need to add this
...
where should i add this? @shrewd apex
corresponding to same level as line 43
i do this
https://paste.pythondiscord.com/4U2A
but now the last message is not sent with the buttons
@shrewd apex
u didnt send the view anywhere
if u dont send the view how will the buttons show up?
As friendly advice, if you're not even familiar with how a try/except works you're going to have a very painful time trying to implement an advanced library like dpy. It'll make a lot more sense if you build up with focused exercises on core concepts rather than trying to build a skyscraper from scratch
Yesterday you didn't know what a print was
werent u already given some resources yesterday for this?
https://github.com/Defxult/reactionmenu if ur looking for a library ig
A library to create a discord.py 2.0+ paginator. Supports pagination with buttons, reactions, and category selection using selects. - Defxult/reactionmenu
what are discord bots
yo guys, im using aiosqlite and im using a cursor, but im getting this when Im reading data from it
did you do something like (row[0] for row in c.fetchall(...))?
it worked from another part of my code, not sure why it dont here
and what is being formatted in your embed?
wrong part of code wait
Hey guys my hybrid command is not working for some reason. im not sure why
!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.
wait no thats the wrong script
class MyCog(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.Cog.listener()
async def on_message(self, message):
if message.content.lower() == 'hello' or message.content.lower() == 'hi' or message.content.lower() == 'hey':
await message.channel.send(f"Hello, {message.author}")
@commands.hybrid_command(name = "ping", description = "Tells you the ping")
async def ping(self, ctx):
await ctx.send(f'> Pong! {round(self.bot.latency * 1000)} ms')
async def setup(bot):
await bot.add_cog(MyCog(bot))```
this is my hybrid command script but not sure why it wont work
'item_name': (name[2] for name in guild_shop if item_dict['item_id'] == name[1]),
'item_description': (desc[3] for desc in guild_shop if item_dict['item_id'] == desc[1]),
'value': (value[4] for value in guild_shop if item_dict['item_id'] == value[1])
``` these are indeed generator expressions
oh
how do I format them correctly
seems like what you're trying to do is a JOIN on guild_shop(item_id) so thats what you should rewrite your query into
wdym?
instead of fetching their inventory and all shop items in a separate query, fetch their inventory and just the shop items referenced by each inventory entry, something like: sql SELECT i.item_id, i.quantity, i.private, gs.name, gs.description, gs.value FROM inventory i JOIN guild_shop gs ON gs.item_id = i.item_id see also:
https://sqlbolt.com/lesson/select_queries_with_joins
https://sqlite.org/lang_select.html#fromclause
what doesnt work about it? does the slash command not get synced? does the on_message not fire as desired? is the text command not recognized?
ye the normal command works but the slash doesnt
did you reload [Ctrl+R] your client?
well er, your discord application specifically, not the bot
discord has had a kind of long-standing problem with new slash commands not appearing on clients, so thats my first guess whenever a slash command doesn't seem to show up
"Doesn't work" isn't descriptive of what's actually happening
oh ok ill try that
I can't see the slash command
Your call to sync will also tell you if you synced that command
if the issue persists, try reading https://gist.github.com/Samarthh2601/b6f57065f394b54f43666037ade38d32#slash-commands-not-showing-up
what is CommandTree.sync()
what does it do?
sync the app commands
read the upper sections of the gist. you'll find the code example and the explanation below it
Better if someone could link Asher's gist explaining commandtree
i tried to sync like this: synced = await bot.tree.sync()
and the slash command appears now
im not sure if its the sync that fixed it or it was just discord being slow..
Well, you always need to sync for the slashes to appear
"Your organization's usage has exceeded its included quota
Your projects can become unresponsive or enter read-only mode. Please upgrade to the Pro plan to ensure that your projects remain available."
"5.242 / 5 GB (105%)"
How we are using so much, is there a way to see whats using this or what..? I am really confused on how we are using so much just for a discord bot..?
It was literally always <%1 but yesterday it started to go up, and its the only thing GOING up. And I have NO clue why.
I am just trying to see what Table could be doing this or what could be causing this stuff, it has never done this before tho.
I am only asking here because I know others use supabase, so if someone could help then please do lol
5gb is not a lot
For just a discord bot..? Id beg a differ 😭
bandwidth or storage?
egress is bandwidth iirc
^^
is this a free plan or smth
does anything else read your database?
damn 5gb is shit
Ofc, but out of all bots, this is the only one having this issue 😭
The rest are using less than 1% is why I am hella confused
Well we have decided to ditch supabase and just host our own. This will just be easier 😁
idk but looking at the supabase website it looks cringe
just get a good vps and throw all ur bots on that
So just ignore my message ig 
We use digital ocean XD
gross but ig it works
so we are gonna host our own postgres instead of using supabase
Its really good tho 😭
don't hate on digital ocean the website that looks like it was made in 2000s 😭
i dont care about what the website looks like
If anything it'd be https://discord.com/channels/267624335836053506/965291480992321536
Wdym?
Like are you using droplets? which one, and what specs? (Just curious)
Droplets
Idk the specs, id have to check lol
Actually, I can't check, this droplet isn't mine, its my friends so I can't check XD
We have like multiple droplets, but this one I do not control sadly
the cheapest plan is shit
so i can't imagine what the rest are compared to competitors
Hetzner VS DigitalOcean lol lmao
https://leo.might-be.gay/WYENY3.png https://leo.might-be.gay/PN1SY0.png
that's with italian 22% sales tax
Locations tho 
Watched a video abt locations on fucking water today ngl.
Where this mofo was talking about how water is different on prices just based on location even if its the same brand
crazy things
they dont have new shared intel locations in the U.S but they do for amd servers
https://leo.might-be.gay/SK3KJI.png
if you want your server to be in the land of the "free"
wanna talk abt it?
There isn't anything to talk about
leo-might-be.italian
real
anyway if you use droplets you're getting scammed lmfao
# allows a command to be executed if the user either has a specific role or admin perms
# for addrole & remrole:
def has_any_role_or_permission(ctx: Context):
if any(role.name in globals.roleRole for role in ctx.author.roles):
return True
if ctx.author.guild_permissions.administrator:
return True
#example:
@bot.command(name='purge')
@commands.check(has_any_role_or_permission)
logic
(roleRole is defined in globals.py)
can i somehow catch the CheckFailure error once a user tries the command without the roles or perms needed
or do i need to just try & except it on every command
forgot
def has_any_role_or_permission(ctx: Context):
if any(role.name in globals.roleRole for role in ctx.author.roles):
return True
if ctx.author.guild_permissions.administrator:
return True
return False
return False that should fix it. Possibly lol
cs im tryna have it send a message like "You don't have the perms to use this command" or sumn
Oh wait I didn't even read everything, but yes, you can catch the CheckFailure, you can use errorhandling
@bot.event
async def on_command_error(ctx, error):
if isinstance(error, commands.CheckFailure):
await ctx.send('You do not have the correct role or permissions to run this command.')
else:
raise error```
Example
could use an or statement here
Was keeping how they had it lol
i see, apologies
nah you good
so i just have this and it applies to all commands, right?
Thats how error handling works yes.
ty! <3
You should not be using channel names to store shifting data. This is API abuse and discord have specifically said it is not allowed
oh shi mb folks, ty for letting me know
Your code looks for one specific channel in one specific guild and updates that one, regardless of which guild you're getting updated counts for though
?
Huh...?
anyone know why i'm getting this
supposedly that means your client UI has an outdated version of the command, so perhaps Ctrl+R reloading your client would fix it?
nope
try loading your discord in the browser
Why does my ping command not work?
# bot.py
import os
from dotenv import load_dotenv
import discord
from discord.ext import commands
load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')
intents = discord.Intents.all()
intents.message_content = True
bot = commands.Bot(
command_prefix = "!",
intents=intents,
activity=discord.Game("placeholder"),
)
@bot.event
async def on_ready():
print(f'Bot is ready. Logged in as {bot.user}')
@bot.event
async def on_message(message):
if "hello" in message.content:
print(f'Message received: {message.content}')
for x in range(10):
await message.channel.send("hello"),
@bot.command
async def ping(ctx):
print('[debug] Ping command received')
await ctx.send("pong")
Why does my ping command not work?
Im using the exact explanation from the docs: https://discordpy.readthedocs.io/en/v2.3.2/ext/commands/commands.html#
I have the correct intents turned on in the developer portal (all of them).
The @bot.event on_message etc. all work fine.
But the bot.command doesn't do anything when i post !ping in the discord server. Also no debug print.
its bot.command() not bot.command
Doesn't make a difference.
where are you starting the bot?
In the folder.. where my application is.
Everything else works.
Yep thats it. Thanks lol
nw
Whats an alternative to Flask, that is async
Now the downside of this is, I can't run these in a thread correct?
Are you trying to run them alongside your bot?
just spin up a plain aiohttp webserver alongside
u can
Yes lol
But does aiohttp.web support css n stuff like that?
why would you need that
Gotta also have it as a docs page for web developers
thats why I have flask
shouldve mentioned that 😭
i mean, it's a webserver, just like flask
Its an API while being a docs page for the web developers, so they understand how it works in the bot and how to make it work in the website side
u could just use bot.loop.create_task(run_function_here)
if u dont want a seperate bot instance and be monolithic
fastapi has swagger
tf is swagger 😭
and openapi docs too iirc
looked it up
So you would say, best is fastapi for my situation?
sounds like a good solution
async def on_command_error(ctx, error):
if isinstance(error, commands.MissingRequiredArgument):
embed = discord.Embed(
description="**Mention someone to unban**\n> **,unban** *(userid)*",
color=discord.Color.red()
)
await ctx.reply(embed=embed)
elif isinstance(error, commands.CommandInvokeError):
error_message = str(error) if str(error) else "An unknown error occurred"
await ctx.reply(error_message)```
erorr handling part of an unban command
returns An unknown error occurred: object async_generator can't be used in 'await' expression
The error is in one of your commands
What are you trying to accomplish?
!paste
code: https://paste.pythondiscord.com/CJKQ
Error: ImportError: cannot import name 'InvalidTimeSpan' from 'humanfriendly' (unknown location)
i don't get my error
import discord
from discord.ext import commands
bot = variables.bot
#code here
bot.run(variables.token)
.../0/botdiscord $ python main.py Traceback (most recent call last):
File "/storage/emulated/0/botdiscord/main.py", line 43, in <module> bot.run(variables.token)
^^^^^^^ AttributeError: 'Command' object has no attribute 'run'
what is variables.bot?
Can you show what is "variables"
is there anyway to track the current duration of a song being played in a vc
i tried just storing the time at the start of it but that doesnt include pausing the song and what not
What are you using to play the music?
meh
ok well im using that
i forgot yt_dlp, any code?
uh its a bit funky since i made it a couple years ago idk how the modern implementations are done but ye
one sec
tried to include the relevant stuff idk if i missed amst
You don't get help with music bots here, wouldn't really talk about it here if possible
Rule 5
Do not provide or request help on projects that may violate terms of service, or that may be deemed inappropriate, malicious, or illegal.
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.
typically you expose a web server to Discord and it sends interactions to your server as POST requests
the other way is through websockets/gateway which idk much about
how do i check the channeltype of the message? i saw something like Message.channel.type but i dont know what it should return
!d discord.Message
class discord.Message```
Represents a message from Discord.
x == y Checks if two messages are equal.
x != y Checks if two messages are not equal.
hash(x) Returns the message’s hash.
!d discord.Message.type
The type of message. In most cases this should not be checked, but it is helpful in cases where it might be a system message for system_content.
the docs say what type it returns
hey, does anyone know how i can use the member object given by the on_member_join function to do things like get the members profile picture?
thank you
typehint it as member: discord.Member to get autocompletions
alternatively, read the docs here
to get a user banned from every server the bot is in, can i loop thru the guilds and ban the user?
yes, but... why??
@bot.command(name='gban')
@commands.check(has_any_role_or_permission)
async def gban(ctx, user: discord.User = None):
for guild in bot.guilds:
ctx.guild.ban(user)
``` would something like this even work?
i edited it, like that?
nvm nvm
discord.User with capital U
also await the ban call
!d discord.Guild.ban
await ban(user, *, reason=None, delete_message_days=..., delete_message_seconds=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Bans a user from the guild.
The user must meet the [`abc.Snowflake`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Snowflake) abc.
You must have [`ban_members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.ban_members) to do this.
completely forgot lmao 😭
Does anyone know how the WHMCS api works for getting attachments? Are you able to download them?
https://developers.whmcs.com/api-reference/getticket/
you can get attachment, but I see no way of getting attachment url or a way of downloading it..?
WHMCS developer documentation - themes, modules, hooks, oauth, api and more...
I am trying to open an attachment from an older ticket. It won't open. Just says file now found. I also tried logging in as client. Newer tickets don't seem to have a problem. So maybe it's because of the ticket age for some reason. I really need to get that attachment. If I can find it directly ...
Thank you 🙏
You're welcome.
Hi, If I do jsk py bot.http.token it says [token ommited] but gives the token when I use jsk py await ctx.send(bot.http.token) how do I fix it?
jsk should be owner only command wdym fix it?
^ what needs fixing here? Only you can run that
I guess if you spend so much time building systems predicated on people being brain dead stupid, you start applying that to yourself
anybodii know how buttons work
i made a post with the code here: https://discord.com/channels/267624335836053506/1248555118387789884
hi so i was trying fetch badges for a user using public_flags in my discord server for a project of mine but seems like the amount of badges u can get is limited is there any other way.
for this project
Not all badges are exposed on the api afaik
Ty pookie
chat how do i restrict a button to a specific role(s)
"chat"
Do whatever checks you want in the callback
What you could do is when the person presses the button, you grab the interaction.user and check their roles.
May want to check the rules there
yeahh dont offer or request paid services
https://paste.pythondiscord.com/MGXQ
why when the user sends a number, the bot does not send an embed message confirming this number
these are the last lines
the bot does not respond to what the user sends
yea i figured i guess the only way is to scrape tho it goes against tos
ur code looks fine
Are you really trying to shuffle around crypto with a discord bot
maybe try debugging
its auto mm bot
I did it but there are no errors or anything so I don't know what's wrong
there are multiple auto mm bot tho i think its for TG
so any ideas why it doesn't work?
"Auto mm" sure is a bunch of words
check ur intents/perms tho that could be the only issue ur code overall looks fine
the bot has all the permissions, the same user
I also think the code is good, but there must be something wrong
https://pastebin.com/c24dJcr7 take a look lmk
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
take a look at RoleSelection/ConfirmationView
unfortunately it doesn't work, if you want I can show you on the server what exactly the problem is
he send it
but he didn't read the value I wrote
You may wish to review the monetization terms you have agreed to. Particularly:
- Facilitation of financial asset transfers or securities ownership.
https://support.discord.com/hc/en-us/articles/10575066024983-Monetization-Policy#summary
ok, but it probably has nothing to do with the code because it only asks about the value
But you are asking for help with a bot that violates terms, aren't you?
Even if it's not this specific piece that is violating the terms
after all, he doesn't break the rules, he's supposed to be an auto middleman bot
Are you facilitating the transfer of financial assets?
Cryptocurrency are financial assets
thats against the tos of discord im pretty sure?
are you trying to make something similar to halal mm? @wet talon
just noticed that youre in the stock server lol
yes
well be careful because that server gets banned every week or so
its pretty complicated.. so be patient until somebody with experience can help u
https://paste.pythondiscord.com/MGXQ
why when the user sends a number, the bot does not send an embed message confirming this number
these are the last lines
the bot does not respond to what the user sends
Can you answer this? It's a pretty relevant yes/no question
if i have a url= argument in my button, it automatically sets the style of the button to url. Is there any way to force it a different style? Even if i specify a style like primary or success it uses url
url buttons can only be one style
understood
if i have multiple buttons with long text, can i do something along the lines of how you can do \n to start from a new line
instead of the buttons going to the right beyond the text & embed
You can set the button row for each button
Each message has a limit of 5 rows with 5 buttons each
!d discord.ui.Button
class discord.ui.Button(*, style=<ButtonStyle.secondary: 2>, label=None, disabled=False, custom_id=None, url=None, emoji=None, row=None, sku_id=None)```
Represents a UI button.
New in version 2.0.
np
its oki
https://paste.pythondiscord.com/MGXQ
why when the user sends a number, the bot does not send an embed message confirming this number
these are the last lines
the bot does not respond to what the user sends
any ideas?
bro my automm bot is broken
So are you actively avoiding this question?
crypto middleman = cross trading, like csgo to crypto
could you help me with slash commands if you ever have time? i made a whole seperate bot to test & it just doesn't work. i was following this tut:
well, you're syncing the tree to the guild, but the command globally
its impossible to make a userinfo with a slash command, pls explain why?
just replace that with await bot.tree.sync() 🗿
why?
wdym userinfo
!d discord.Interaction.user
The user or member that sent the interaction.
cus i tried, and it never worked the way i intended
im 99% sure i got rate limited. what now
either that or
i actually need help with something
can i post my code here
!traceback
Please provide the full traceback for your exception in order to help us identify your issue.
While the last line of the error message tells us what kind of error you got,
the full traceback will tell us which line, and other critical information to solve your problem.
Please avoid screenshots so we can copy and paste parts of the message.
A full traceback could look like:
Traceback (most recent call last):
File "my_file.py", line 5, in <module>
add_three("6")
File "my_file.py", line 2, in add_three
a = num + 3
~~~~^~~
TypeError: can only concatenate str (not "int") to str
If the traceback is long, use our pastebin.
yeah uh its not that
paste yours
im having trouble because i tried to code this which i found somewhere, it works and apparently my bot IS synced to it as well but it doesnt show up in apps
async def show_join_date(interaction: discord.Interaction, member: discord.Member):
await interaction.response.send_message(f"{member} joined at {discord.utils.format_dt(member.joined_at)}")```
when I sync automatically from on_ready def it also counts this as synced but it doesnt show on apps, yet it still doesnt show any errors. it should be working but its not.
i even made a manual sync function and it still said the same thing yet it doesnt show in apps. why?
did u try reloading ur discord client (just hit ctrl + r)
if the command shows up in the synced command lists when u sync it from ur code for that particular bot then that means discord has received that data so in most cases its ur client lagging behind 
oh i did get an error
Traceback (most recent call last):
File "/home/container/.local/lib/python3.12/site-packages/discord/app_commands/commands.py", line 828, in _do_call
return await self._callback(interaction, **params) # type: ignore
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/container/bot.py", line 47, in show_join_date
await interaction.response.send_message(f"{member} joined at {discord.utils.format_dt(member.joined_at)}")
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'InteractionResponse' object has no attribute 'send_member'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/container/.local/lib/python3.12/site-packages/discord/app_commands/tree.py", line 1248, in _call
await command._invoke_with_namespace(interaction, namespace)
File "/home/container/.local/lib/python3.12/site-packages/discord/app_commands/commands.py", line 853, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/container/.local/lib/python3.12/site-packages/discord/app_commands/commands.py", line 846, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'show_join_date' raised an exception: AttributeError: 'InteractionResponse' object has no attribute 'send_member'
@fast osprey sorry the forum was closed yes I want to send another message do i need use interaction.followup("")
But I saw the type of .followup is webhook i don't really know what that is
class discord.Webhook```
Represents an asynchronous Discord webhook.
Webhooks are a form to send messages to channels in Discord without a bot user or authentication.
There are two main ways to use Webhooks. The first is through the ones received by the library such as [`Guild.webhooks()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild.webhooks), [`TextChannel.webhooks()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.TextChannel.webhooks), [`VoiceChannel.webhooks()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.VoiceChannel.webhooks) and [`ForumChannel.webhooks()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.ForumChannel.webhooks). The ones received by the library will automatically be bound using the library’s internal HTTP session.
The second form involves creating a webhook object manually using the [`from_url()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Webhook.from_url) or [`partial()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Webhook.partial) classmethods.
For example, creating a webhook from a URL and using aiohttp:
Ty
send_member? can u paste your code
oh yeah
i fixed it myself i just saw the trace
but yeah youre right lmao im blind i said send_message
or not
yup.
Traceback (most recent call last):
File "/home/container/.local/lib/python3.12/site-packages/discord/app_commands/commands.py", line 828, in _do_call
return await self._callback(interaction, **params) # type: ignore
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/container/bot.py", line 47, in show_join_date
await interaction.response.send_member(f"{member} joined at {discord.utils.format_dt(member.joined_at)}")
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'InteractionResponse' object has no attribute 'send_member'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/container/.local/lib/python3.12/site-packages/discord/app_commands/tree.py", line 1248, in _call
await command._invoke_with_namespace(interaction, namespace)
File "/home/container/.local/lib/python3.12/site-packages/discord/app_commands/commands.py", line 853, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/container/.local/lib/python3.12/site-packages/discord/app_commands/commands.py", line 846, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'show_join_date' raised an exception: AttributeError: 'InteractionResponse' object has no attribute 'send_member'
send_member its send_message
did u save ur file?
yeah
not possible
hmmm
u prolly made a typo somewhere or just looked at the previous errors
like maybe i didnt youre right, maybe im losing my mind i was sure it was message i mean thats literally why i changed it to member otherwise it wouldnt have been
no you are right im losing my mind my bad
?
Yo i need help
im tryna code this discord bot cause I hv too much free time and want to learn smth
you know how each bot has its very own intent
how do I make mine the tag of the bot
like instead of using !help
how to make it @bot help
tag me so i don't forget
thanks @wanton current
np
@wanton current can u help me pretty pls 🥺
import discord
from discord.ext import commands, tasks
from discord import Interaction
@bot.hybrid_command(name="placeholder", description="placeholder2")
yo guys, need help #1248712676931010592
what d oyou mean? Its just not in your code. Just add it like the rest?
its not? what is it thenn
Wait, i did not understand your question. You can find that info from User.premium_type. It will be an int you can match to this table -> user-object-premium-types
import variables # file
@bot.command()
async def var(ctx, * var: str):
await ctx.send(variables.ctx) #get var from file
2024-06-07 21:26:21 ERROR discord.ext.commands.bot Ignoring exception in command var
Traceback (most recent call last):
File "/data/data/com.termux/files/usr/lib/python3.11/site-packages/discord/ext/commands/core.py", line 236, in wrapped
ret = await coro(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/storage/emulated/0/botdiscord/main.py", line 51, in var
await ctx.send(variables.ctx)
^^^^^^^^^^^^^
AttributeError: module 'variables' has no attribute 'ctx'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/data/data/com.termux/files/usr/lib/python3.11/site-packages/discord/ext/commands/bot.py", line 1169, in invoke
await ctx.command.invoke(ctx)
File "/data/data/com.termux/files/usr/lib/python3.11/site-packages/discord/ext/commands/core.py", line 1020, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/data/data/com.termux/files/usr/lib/python3.11/site-packages/discord/ext/commands/core.py", line 245, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: module 'variables' has no attribute 'ctx'
what is variables
bruh, are u kiding mr
well, the error is pretty obvious
...
?
You probably don't want a singular context shared globally across your app
what do you think wich functions should an automod bot have? Wich would he important if you would use it?
What is "variables"?
A FILE
Show it
no theres my token
Just delete it in the message :/
but why
How do you want to receive help if you don't show everything?
Additionally, the token is recommended to have its own file. I recommend a .env file
u don't need to see that
Then check that the variables module has the ctx attribute
If you don't show that module I can't help you.
huh
the ctx attribute is in the async def
.
what is variables.ctx
It doesn't want to show the module for some reason
"it"
from discord.ext import commands
bot = commands.Bot(command_prefix="+", help_command=None)
@scarlet tiger
self_bot=True
nooo
I only see the Bot object instance. Nothing related to "ctx"
bc it's not in this file...
import variables # file
@bot.command()
async def var(ctx, * var: str):
await ctx.send(variables.ctx) #get var from file
The problem is here "variables.ctx"
^
what did u change ?
what???
I repeat. The error is in the line await ctx.send(variables.ctx). The variables module does not have that attribute.
so what can i do to make it works?
Show me the variables module
it's at the top of my code
the content of the module. Do you know Python?
🤔
"the content of the module"
💀💀💀💀
the file?
🤡 yes
alr showed you.
@scarlet tiger
You are trying to use something from the variables module which is "ctx" but in the code you gave me that does not exist.
noo, i see wym
like +var <var name>
then it returns the var value
Well it doesn't have it. Check that it has the ctx attribute. It's basic Python
?
this might be one of the funniest back & forths i've seen
whats the original issue again lmao
hi
You are trying to access ctx of the variables module but in the code you gave me that does not exist.
@scarlet tiger
ctx.content*
?
like +var token
{token of the bot}
can you recommend me a code editor app to write code from my phone?
never even touched the variables module i cant say nun
Sorry, I don't know a code editor on mobile :(
ah, np
coding on a phone is a royal pain in the ass
but ı have to..
yes that's why i like it
and who asked?

Is it any use to me?
??
how do I download the module to the app?
doesn't work in some applications
termux
@simple prawn where is py💀
u have to create in ur
file manager sry
ok thanks
u're wlc
stop working idk why https://sourceb.in/lvyK5kmuUI
word
.
the bot lagging has no such relation to having all commands in a single file unless ur doing something very resource intensive or very bad code, its most likely network latency
if u made a 2nd file i am assuming u meant as cog? so did u load the cog?
no i mean the ram usage was 1.5gb thats why i added it in another file
see
@shrewd apex
that wouldnt help at all if ram usage is high then ur using a ton of memory somewhere else, also replit machines are pretty underpowered wouldnt really trust their analytics
u need to load help.py as a cog if ur using stuff in another file
!paste paste ur help.py content here
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.
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.
@shrewd apex
the code u wrote wont work
can you give the solution please ?
from discord.ext.commands import Bot, bot # <-- No such thing as "bot"
u need to make a cog
A hands-on guide to Discord.py
but this wont help with your ram usage or memory problem btw
Should this interfere with any other commands i have in place? https://paste.pythondiscord.com/V2TA
Asking because these commands work when i dont have the event in the code, but when i put the event in, the event itself works fine, but the other commands cease to exist, it doesnt even recognise the prefix as a prefix (like otherwise youd get a message saying ?me isnt a command)
are you asking regarding the aforementioned snippet or in general? the snippet i dont host anywhere, its just a project that i run on my pc. But on bigger projects i simply used to buy some replit cycles, dont know if its changed now
does anyone know a good hoster?
Files aren't cogs, these are separate concepts entirely
The examples given don't go into the nuance that you do not need a cog at all to have an extension. In many cases the cog is just unnecessary messy boilerplate
You're overriding on_message, which is the thing that runs commands in the first place. Consider using a listener instead of an event if you don't want to override the default behavior and just add to it
could you help me with this script
from discord.ext import commands
intents = discord.Intents.default()
intents.message_content = True
intents.guilds = True
intents.guild_messages = True
intents.members = True
bot = commands.Bot(command_prefix='.', intents=intents)
vouches = {}
@bot.event
async def on_ready():
print(f'We have logged in as {bot.user}')
@bot.event
async def on_message(message):
if message.author == bot.user:
return
await bot.process_commands(message)
@bot.command()
async def vouch(ctx, member: discord.Member = None):
if member is None:
await ctx.send("Hey! To use this feature, please mention a user. Example: `.vouch @user`")
return
vouch_count = vouches.get(member.id, 0)
vouch_count += 1
vouches[member.id] = vouch_count
await ctx.send(f"Congratulations! {member.mention} has been vouched {vouch_count} time(s).")
@bot.command()
async def vouchcheck(ctx, member: discord.Member = None):
if member is None:
await ctx.send("Hey! To use this feature, please mention a user. Example: `.vouchcheck @user`")
return
vouch_count = vouches.get(member.id, 0)
await ctx.send(f"{member.mention} has {vouch_count} vouch(es).")
@vouch.error
async def vouch_error(ctx, error):
if isinstance(error, commands.MemberNotFound):
try:
member_id = int(ctx.message.content.split()[1])
member = bot.get_user(member_id)
if member:
await vouch(ctx, member)
else:
await ctx.send("Invalid user ID!")
except ValueError:
await ctx.send("Member not found or invalid user ID!")
bot.run('its here just not in the message')```
It's unclear what you want to do or where the problem is
i want it to say Thank you for vouching @user and then when i do .vouchcheck @user it gives me the number
Your error handler is probably eating errors you don't expect
And also, if you are making the member arg required, why do you pass None as default?
That way you're making that param optional...
And it raises commands.MissingRequiredArgument error if the param is not provided
So you can just catch that 🤷
And as Solstice said, your error handler probably eating errors
Bad error handling is worse than no error handling. At minimum, you should be logging every error you get, independently of how you respond to the users for some of them
ohhh
hi someone can give me a lookup discord account commande just with id bot in python pls ?
what do you mean?
why is my keyboard like this
I have some old code for this ->
@app_commands.command(name="info", description="Get the info of a user")
async def info(self, inter: discord.Interaction, user: discord.User | discord.Member=None) -> None:
await inter.response.defer(ephemeral=True, thinking=True)
user = user or inter.user
embed = Embed(colour=user.top_role.colour).set_thumbnail(user.display_avatar.url)
embed.add_field("Username", user, inline=True).add_field("Display name", user.global_name, inline=True).add_field("Discord ID", user.id).add_field("Status", user.status, inline=True).add_field("Avatar URL", f"[{user.name}'s avatar URL]({user.display_avatar.url})", inline=True)
embed.add_field("Nickname", user.display_name, inline=True).add_field("Colour", user.top_role.colour, inline=True).add_field("Number of Roles", len(user.roles)-1, inline=True).add_field("Server join", generate_timestamp(user.joined_at), inline=True).add_field("Account created", generate_timestamp(user.created_at), inline=True) if isinstance(user, discord.Member) else ...
embed.add_field("Activity", ", ".join([activity.name for activity in user.activities])) if user.activities else ...
await inter.edit_original_response(embed=embed)
PLEASE DO NOT COPY PASTE IT
ok thx
the commande dont work idk why
I said to not copy paste because it's old
i have something similar:
@bot.command(name='userinfo')
async def userinfo(ctx, user: discord.Member = None):
if user is None:
user = ctx.author
embed = discord.Embed(color=discord.Color.pink())
embed.add_field(name="Nickname", value=user.mention, inline=False)
embed.set_author(name=str(user), icon_url=user.avatar.url)
obj = user.created_at # for account age
obj_date = str(user.created_at)[:10] # for account join date
current_date = datetime.now()
age_years = current_date.year - obj.year
age_months = current_date.month - obj.month
if current_date.month < obj.month or (current_date.month == obj.month and current_date.day < obj.day):
age_years -= 1
age_months += 12
if age_months < 0:
age_years -= 1
age_months += 12
age = f"{age_years} years, {age_months} months"
embed.add_field(name='Account Age', value=f"{age}, ({obj_date})", inline=False)
# if user doesnt have a custom server pfp use the user pfp
if user.guild_avatar:
thumbnail_url = user.guild_avatar.url
else:
thumbnail_url = user.avatar.url
embed.set_thumbnail(url=thumbnail_url)
join_date = str(user.joined_at)[:10]
embed.add_field(name="Joined Server", value=join_date)
roles = [role for role in user.roles if role.name != '@everyone']
roles = sorted(roles, key=lambda x: x.position, reverse=True)
max_roles = 25
total_roles = len(roles)
if total_roles > max_roles:
roles = roles[:max_roles]
role_mentions = [r.mention for r in roles]
if role_mentions:
role_string = ''
for role_mention in role_mentions:
if len(role_string) + len(role_mention) <= 1024:
role_string += role_mention + ' '
else:
break
if total_roles > max_roles:
field_name = f"Roles [{total_roles}] (Showing first {max_roles})"
else:
field_name = f"Roles [{total_roles}]"
embed.add_field(name=field_name, value=role_string.strip(), inline=False)
embed.set_footer(text='ID: ' + str(user.id) + ' | Made by vilkaviskietis')
await ctx.send(embed=embed)
this is the output
you can get the user status too?
ty this worked although it let me vouch in every channel so i tried to fix it it responds in every channel except for the vouch one
from discord.ext import commands
intents = discord.Intents.default()
intents.message_content = True
intents.guilds = True
intents.guild_messages = True
intents.members = True
bot = commands.Bot(command_prefix='.', intents=intents)
vouches = {}
scam_strikes = {}
# Define the ID of the specified channel
specified_channel_id = 1248953825541361758
@bot.event
async def on_ready():
print(f'We have logged in as {bot.user}')
@bot.event
async def on_message(message):
if message.author == bot.user:
return
# Check if the message was sent in the specified channel
if message.channel.id == specified_channel_id:
await bot.process_commands(message)
@bot.command()
async def vouch(ctx, member: discord.Member):
vouch_count = vouches.get(member.id, 0)
vouch_count += 1
vouches[member.id] = vouch_count
await ctx.send(f"Thank you for vouching {member.mention}!")
@bot.command()
async def vouchcheck(ctx, member: discord.Member):
vouch_count = vouches.get(member.id, 0)
scam_strikes_count = scam_strikes.get(member.id, 0)
profile_embed = discord.Embed(title=f"〔✧〕╰──╮ {member.display_name} Profile╭──╯〔✧〕",
description=f"Heres {member.display_name}'s profile page",
color=discord.Color.blurple())
profile_embed.add_field(name="Vouches", value=f"{vouch_count} vouch(es)")
profile_embed.add_field(name="Scam Strikes", value=f"{scam_strikes_count} scam strike(s)")
await ctx.send(embed=profile_embed)
@vouch.error
@vouchcheck.error
async def command_error(ctx, error):
if isinstance(error, commands.MissingRequiredArgument):
await ctx.send("Please mention a user.")
else:
# Log the error for debugging purposes
print(f"Error occurred: {error}")
bot.run('thingy')```
Is that a question? Confused if something isn't working with this
just a general suggestion, store the vouches in like a json or txt file or sum
ok ty would you mind teaching me more on taht
bc once you restart the bot the vouches = {} will reset to an empty dictionary
atleast i think
You shouldn't use flat text files to store application data
yea
Use a database if you want it to persist
or just a json file


ive coded loggers
to actually work?