#discord-bots
1 messages · Page 383 of 1
Can you copy my code add replace pls
Nuh uh
.
Gotta learn doing it yourself
Which thing need to remove ?
Read your code and check
Help with?
It's showing still error
When I did this
This is my code can you check out and tell me what wrong?
@slate swan
What error
?tag embed
This is not a Modmail thread.
Didnt i already tell you that timezone is submodule of datetime
So you need to import it
!d datetime.timezone
class datetime.timezone(offset, name=None)```
The *offset* argument must be specified as a [`timedelta`](https://docs.python.org/3/library/datetime.html#datetime.timedelta) object representing the difference between the local time and UTC. It must be strictly between `-timedelta(hours=24)` and `timedelta(hours=24)`, otherwise [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) is raised.
The *name* argument is optional. If specified it must be a string that will be used as the value returned by the [`datetime.tzname()`](https://docs.python.org/3/library/datetime.html#datetime.datetime.tzname) method.
Added in version 3\.2\.
Changed in version 3\.7: The UTC offset is not restricted to a whole number of minutes.
Do you even know what you are doing
Importing
If you are a beginner start from beginner things and not a discord bot project which requires advanced python concepts
Ok but it's only 1 error my project will be finished
Can you copy and fix my code pls ?
No that's not how helping works
I didn't understand where this thing need to paste or replace
You dont copy paste random code to your project
Ok
I just wanted to show you that datetime module Has a submodule called timezone which apparently you want to use
Help me only 1 time
So to your current datetime import add that timezone submodule and change the code from datetime.timezone. to timezone.
Ok
is there on discord any option to switch between discord accounts like on instagram? Do I have to log out and log in every time?
when you click on your profile there literally is option Switch accounts
I don't see it on my phone
i dont know if its out on mobile yet
you can do that on pc for sure
The Discord gateway only dispatches events you subscribe to, which you can configure by using "intents."
The message content intent is what determines if an app will receive the actual content of newly created messages. Without this intent, discord.py won't be able to detect prefix commands, so prefix commands won't respond.
Privileged intents, such as message content, have to be explicitly enabled from the Discord Developer Portal in addition to being enabled in the code:
intents = discord.Intents.default() # create a default Intents instance
intents.message_content = True # enable message content intents
bot = commands.Bot(command_prefix="!", intents=intents) # actually pass it into the constructor
For more information on intents, see /tag intents. If prefix commands are still not working, see /tag on-message-event.
Ohk
Looking over your code, I really strongly recommend you reconsider building this "antinuke" stuff. The entire purpose is predicated on your users being too stupid to handle their server themselves, and if you're already assuming that there's no reason to assume they're somehow not stupid enough to break any of the things your bot relies on.
Also, outright banning anyone who gets the admin permission is pretty laughable
So suggest me
How can I make
This good best
@fast osprey
Does u make bot like this ?
Educate your users on good security practices and make recommendations to them rather than trying to override the decisions they themselves have made
No, because bots like this (at least that subset of functionality) are at best unnecessary and at worst an active security risk
I have, however, in my time seen things like this crash and burn miserably
But I want to make a antinuke bot for my friend server
Antiraid
Antispam but my bot is not replying not enable 😅😭
Now I lost my hope
I'm not making now bot
You should not make features that attempt to excuse people from managing their own servers and understanding how permissions work. You can absolutely make a bot that aids in this rather than trying to replace it
But if you make a bot under the entire pretext of "You don't have to understand security or permissions, my bot takes care of it", they will continue not understanding things and there will always be a way they can screw things up
For spam, you should really look into the automod tooling that's available
i fixed it by doing nothing
you know message that only you can see? like to the bottom it’ll say dismiss how do I do that in slash cmd
You can pass ephemeral=True when responding
Yeah. Its not deleting it when there’s a bad word in the linked image
Is the API returning the correct words?
It does with message attachments so im guessing it should work on text links but I’ll test that
What part is specifically not working?
It does not delete the message when there is a bad word in the image
It does not delete the message when there is a bad word in the url?
We are here to help no need to be sorry :)
I guess I didn’t fix it, the api is returning the right words
So its something with either finding it or deleting it
It looks like this right now ```py
urls = func.extract_url(message.content)
if urls:
if len(urls) == 1:
text = func.image_to_text(url[0])
if any(bad_word in text.lower() for bad_word in badwords):
await message.channel.send(f"[AUTO] {message.author.mention}, your message has been deleted for containing a blocked keyword.")
await message.delete()
else:
for i in range(len(urls) - 1):
text = func.image_to_text(url[i])
if any(bad_word in text.lower() for bad_word in badwords):
await message.channel.send(f"[AUTO] {message.author.mention}, your message has been deleted for containing a blocked keyword.")
await message.delete()```
do you have the message content intent?
Yeah
I am a bit confused. When you send a URL that leads to an image with bad words it correctly identifies the bad words (You can check by printing text) However the message is not deleted?
Mhm. It finds the text fine from testing
does it go into the if statement? Are there any errors in your console?
In general, doing some debugging to see what is actually running would go a long way
@sacred grotto I saw your help post but it was locked.
Your issue is that you are enabling all of the intents. Discord has a few "special" intents that require additional approval when your bot gets big enough (its for data privacy reasons) So you need to go to the discord developer portal -> your app -> Bot -> Turn the settings in the screenshot ON
It is incredibly unlikely that all intents are needed, whatever this app is doing
^ The best solution would be to only use intents that you need but what I said is the direct solution to the error
how to make it so users who use my bot cannot ping everyone?
You can look into allowed_mentions argument of send/respond
Or you can take away the permission to mention everyone on the bot if it is only on your private server or something
Thank you!!!
@last sorrel hey nick you still into python bot dev?
Bruh use automod discord
how can a slash/hybrid command have spaces?
Those are command groups
is there a example somewhere
I think umbra's gist has em if you've read that
class Board(commands.GroupCog,name="board"):
rest is same as commands.Cog
Note: It is only available in discord.py
Oh
You also don't have to use cogs. You can just subclass app_commands.Group too
Im making a discord bot that returns accuracy from a given PGN (list of moves) in the chat. I have the bot writing this data given in the chat to a temporary file that the accuracy script reads from. When I download raw pgn data from the chess website it works just fine but when I use the data from the discord bot (looks the exact same) it raises an error. Could discords formatting be causing this issue?
What's the error?
I do this the only issue I get is sub commands get all the integration setting from its parent command if I want to set perms of sub command individually discord don't get give me option in integration settings
I'm getting something really weird but after I stop my bot the program does not terminate and it sens this after a bit ```
Exception in thread keep-alive-handler:shard-None:
Traceback (most recent call last):
File "C:\Program Files\Python312\Lib\threading.py", line 1073, in _bootstrap_inner
self.run()
File "C:\Users\SiqiC\OneDrive\Docos\CODE DUMP BOI\Python\discord bots\sinflex\everything_bot.venv\Lib\site-packages\discord\gateway.py", line 170, in run
f = asyncio.run_coroutine_threadsafe(coro, loop=self.ws.loop)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Program Files\Python312\Lib\asyncio\tasks.py", line 950, in run_coroutine_threadsafe
loop.call_soon_threadsafe(callback)
File "C:\Program Files\Python312\Lib\asyncio\base_events.py", line 840, in call_soon_threadsafe
self._check_closed()
File "C:\Program Files\Python312\Lib\asyncio\base_events.py", line 541, in _check_closed
raise RuntimeError('Event loop is closed')
RuntimeError: Event loop is closed
C:\Program Files\Python312\Lib\threading.py:1075: RuntimeWarning: coroutine 'DiscordWebSocket.send_heartbeat' was never awaited
self._invoke_excepthook(self)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
no idea what is hapenning ¯_(ツ)_/¯
import asyncio
import logging
from bot.bot import Bot
async def main() -> None:
await bot.load_extensions("bot/cogs")
await bot.connect_to_database()
await bot.start(bot.settings.discord_bot_token)
await bot.close_database_connection()
await bot.close()
if __name__ == "__main__":
bot = Bot()
loop = asyncio.get_event_loop()
try:
loop.run_until_complete(main())
except KeyboardInterrupt:
logging.info("Shutting down bot...")
loop.stop()
loop.close()
using discord.py with custom Bot object
import discord
from discord.ext import commands, tasks
import asyncio
class Nickname(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.Cog.listener()
@self.bot.event
async def on_member_join(member):
print(f'{member} has joined the server.')
If I want to listen to events in another class other than main file, how do I call bot.event? self.bot.event doesn't seem to be working for some reason
do I need to import my main class to call bot from there?
You just need to use the commands.Cog.listener() decorator
I don't need @bot.event of any kind?
yeah
thanks so much
Doesn't seem to be seeing people joining
nvm, forgot to set the members = True intent lol
Tracemollac error usually happens when something is coroutine and it's not used with await
!d discord.ext.commands.Bot.start
await start(token, *, reconnect=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
A shorthand coroutine for [`login()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.login) \+ [`connect()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.connect).
anyone familiar with pysilon?
👀
Hello guys
How can I earn making Discord bots, please?
Make a bot with features that people want to use, pick some or all of the features you want to pay gate, register them with the SKU options discord gives you
What is sku?
Tnx
Not yet out where I am : (
any event which gets fire when thread or forum post get closed/lock after the time expire?
Hi does anyone know why i get this error
discord.errors.PrivilegedIntentsRequired: Shard ID None is requesting privileged intents that have not been explicitly enabled in the developer portal. It is recommended to go to https://discord.com/developers/applications/ and explicitly enable the privileged intents within your application's page. If this is not possible, then consider disabling the privileged intents instead.
All of my intents are enabled on the discord bot page settings, i just want to make a bot where i can DM the bot and say ping, and the bot replies with pong in dm;s
import discord
from discord.ext import commands
intents = discord.Intents.default()
intents.messages = True
intents.message_content = True # This is required to read message content
intents.guilds = True
intents.dm_messages = True # Ensure to enable this intent for DMs
bot = commands.Bot(command_prefix='!', intents=intents)
@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
print(f"Received a message from {message.author}: {message.content}")
if isinstance(message.channel, discord.DMChannel):
if message.content.lower() == 'ping':
await message.channel.send('pong')
bot.run('')```
Forgot to show code
Okay so I am working on making my bot support multiple languages using like English.json and French.json, like how many other bots do it I would think.
But my question still comes down to, @app_commands.describe(member="Please give a member.")
Is there a way to translate that? or am I just stuck with the default language (English)? Same with descriptions on command?
Warn a member.
**Usage:** warn <member> [reason]
**Examples:**
- `warn @member Breaking rules`
- `warn @member Spam pinging`
- `warn @member Sending inappropriate messages`
"""```
These type of descriptions ^^
They are hard coded so that is why I was wondering, I could also do something with the jsons maybe, but just wanted to see how others maybe handle the describe and descriptions of commands with multiple languages?
You don't need any privileged intent for that, so you shouldn't be requesting any in the first place
nwnw. Default() even has intents 99% of devs don't actually want
: (
i added ptero gitsync to my hosting server, but it sends this error
database/bot.db
Please commit your changes or stash them before you merge.```
i added database/bot.db to the .gitignore file as i dont want it to be modified from my local version, is there somehow else i can do this or can i resolve this?
also, did you previously commit bot.db before updating your gitignore? if so, i believe the gitignore can't retroactively remove files that are already being tracked, you would need to manually untrack them by using git rm --cached <path> and then committing
btw for git-related issues, you may get more help asking in #tools-and-devops instead
Anyone have anything on this? I don't know where else I can ask. The dpy server is based on the package so I thought here would be the best
for application commands, dpy's CommandTree can be given a custom Translator class to localize your command names, descriptions, parameters, and choices on sync
https://discordpy.readthedocs.io/en/stable/interactions/api.html#discord.app_commands.CommandTree.set_translator
https://discordpy.readthedocs.io/en/stable/interactions/api.html#discord.app_commands.Translator
as for other forms of content like messages, embeds, and views, you can manually invoke the translator via bot.tree.translator.translate() and Interaction.translate()
if you want an example bot, here's one i wrote using gettext as my backend (it also has a guide to help with learning gettext)
https://github.com/thegamecracks/discord.py-i18n-demo
Project Fluent is also another localization standard if you want to use that instead of .json files
https://projectfluent.org/
https://github.com/projectfluent/fluent/wiki/Fluent-vs-gettext
https://fluent-compiler.readthedocs.io/en/latest/
json is pretty awful as a storage format in terms of space and efficiency. It's designed to be a language agnostic interchange format
I have always seen other bots do it that way, and its just a data language, so I figured it would be perfect for this, because its just data basically.
It's not, and people doing a thing does not remotely imply it is the best or even a good thing to do
okay ty, I will read this all because I am wanting to see how to do this the best way. Thank you again for providing this, I didn't know the translator was for the description and parameters.
Wdym json is not a data language?
or are you saying the translations aren't data?
"data language" doesn't make sense
As I said, json is for transferring data between systems
it is not optimized for one system internally storing and accessing it
What I mean by data language is, its returning data. I had no other way of describing it lol
So we are on the same terms I guess
Not really, no, as there is an important distinction for how the data is used
But I will check out what thegamecracks gave me, which should improve what I have hopefully.
The only examples I have seen were people using .json so thats why I used .json, so thats my bad
all good, it's more nuance. This won't make or break an application, but a lot of people fall into the trap of following examples without really knowing how or why they are a good idea (or in this case, a bad idea)
That is fair, I just thought maybe opening my bot to more languages would help others out ya know, but never thought of the best way of doing it. So I looked at examples and they all showed the same way and it kinda was weird.
But thats also why I asked here, not the same topic, but close enough and it led me to the correct spot.
But glad I asked here lol
Yeah there are data formats (like resource files) that are better suited for storing this particular type of data within an application. Worth looking into
@app_commands.command(
name="promote", description="promote the user"
)
@app_commands.choices(
position=[
app_commands.Choice(name="Server Entry Staff",
value=str(RoleIds.ENTRY_STAFF)),
app_commands.Choice(name="Server Recruiter",
value=str(RoleIds.SERVER_RECRUITER)),
app_commands.Choice(name="Server Manager",
value=str(RoleIds.SERVER_MANAGER)),
app_commands.Choice(name="Server Moderator",
value=str(RoleIds.SERVER_MODERATOR)),
app_commands.Choice(name="Server Gatekeeper",
value=str(RoleIds.GATEKEEPER)),
],
)
@app_commands.describe(user="User you want to promote", position="position you want to give to the user")
async def check_modal(self, interaction: discord.Interaction, user: discord.Member, position: str) -> None:
i want to get position choice name data
just printing position gives the value of it
You shouldn't be using the display name to drive logic
The value is what you should be using. Whatever you need, put it in the value
Hi. I would like to ask if I can create an event in which I capture information from another source? For example, I have a web panel and at a given button send, for example, a message?
not an event specifically but u would have to run a web server side by side to get reqests from the webpanel
and have ur bot process it and respond to it
In what sense side by side
u basically mean when someone performs some action on the webpanel the bot is notified right?
When someone performs an action in the panel then the bot triggers the corresponding event
yeah then u need a web server running along with your bot accepting web requests from your web panel
side by side in the sense u can spawn it in another task
basically u need to listen to http requests
And such basic listening? I host the bot on the same server as the panel
Or else... Could I have some sort of tutorial on this, or basic functions? I also have the panel set up in python on Flask
Personally I recommend you do not colocate your gateway bot and a http webserver. These things do very different jobs, and you'll probably find that they actually don't need to communicate much if at all given the web server can make api requests to discord itself without going through a gateway bot
I'm looking for options to make it work in general.
What's an example of something you'd want to do?
I have a form made in the panel and I want the bot to be connected to it and send to the appropriate channel the information in it just after clicking the submit button
The site and form made with python, so it's easy to plug in with confidence
You don't need a bot at all to send a message
the web server could just post to a webhook
And how else can the bot be integrated? More than once it will have to give roles
Such an intention
You can give roles without going through a bot
bots exist to listen for events from discord. If you are pushing things to discord, the bot doesn't have to be involved at all
If you really want your web server to talk to a gateway bot, these should be in separate processes and communicate over IPC for the things they need to do. But people often vastly overestimate what they need the bot for
Then what is the best way to do it? Do you have a basic script or tutorial?
What webhook?
Well, how to plug such an action? For example for a test when I click a button it sends a message to a specific channel
libraries like discord.py have utility python wrappers that make this easier, but notably they do not require a gateway bot running
I've a webhook
I’m trying to make a discord bot that gets rid of gen-z slang but I no longer have any chatgbt tokens. I do not want to spend any money on this project so any suggestions on creating an ai model?
You should first very carefully read the relevant discord developer policy if you have not already
I now have but I don’t see how this applies
I’m using it to just showcase ai
The AI will hopefully not learn anything either as well
Namely a) if you are sending any user data to a third party, you need explicit instruction from that user to do so and to record that and b) message content can't be used to train models, regardless of who is doing it
In that case would you know how to simply find where a word is with in a message and replace it with another word?
Since making an Ai seems to be extremely painful
Any help is extremely appreciated 😃
As in someone says a word, and you want to reply with another word? Or are you trying to moderate?
Reply with another word
I’ll state what I’m trying to do.
Turns sentences with Gen-Z slang and rewrite it without the slang
“Ong that was hype” to “On god that was cool”
You could attempt to do this with regex, but anecdotally people will misspell or otherwise alter common words
I do have the ability to detect the words right now but do not know where they are in a sentence hmm thinking about that should I bring this into a thread
Regex with capture groups would do that
I’m going to make a thread for this so I don’t flood the chat with this
hello, how do i tell Main.py to decode with utf-8?
unicodes are not display correctly when sent to discord
yo can someone help me
i keep getting an error even though i did everything right
error: MissingMessageContentIntentWarning: Message content intent is not enabled. Prefix commands may not work as expected unless you enable this. See https://docs.nextcord.dev/en/stable/intents.html#what-happened-to-my-prefix-commands for more information.
warnings.warn
You need to enable it in the code as well
its in the code
can you show
intents = nextcord.Intents.default()
intents.members = True
intents.message_content = True
and the bot =?
Ignoring exception in command None:
nextcord.ext.commands.errors.CommandNotFound: Command "test" is not found
import nextcord
from nextcord import Interaction
from nextcord.ext import commands
import os
intents = nextcord.Intents.default()
intents.members = True
intents.message_content = True
client = commands.Bot(command_prefix="!", intents=intents)
@client.event
async def on_ready():
print("The bot is ready for use")
print("-------------------------")
ServerId = 'aaaaa'
@client.slash_command(guild_ids=[ServerId])
async def test(interaction: Interaction):
await interaction.response.send_message("Wsg broda")
client.run('aaaa.aa.aa')```
hmm
Yo, so I am reading abt this, and one of the developers that work with me brought up a good point, will this work with code space and like mac books and stuff?
I am asking because of the MSYS2 part, I don't know if code space would allow that, and I have no clue if mac can support it because I only see an EXE version.
Because we all work together, but if only I can access the source, that makes production bad and makes this a bad way of doing this for our bot.
if it can install gettext sure, MSYS2 is just a way to get it on windows
Okay, so I would just have to research other ways to get gettext on mac and code space?
im currently experimenting with rewriting my bot to use project fluent, its been fairly tedious changing out the strings
I just do not want to do this and make it a compatibility issue for other developers on the team, for my vps it would be fine, but other developers it might come into an issue.
It seems fairly easy to setup and do. I actually like how you have done the docs on it and showed it. But I never thought about the compatibility tbf.
finished my project fluent migration if you want to see how that looks
https://github.com/thegamecracks/theticketbot/compare/df65ba2...1907288
project fluent doesn't require external compilation so its simpler in that regard
though afaik it doesn't come with any official tools, nothing like xgettext and msgmerge
as for gettext, some of the GUI editors i linked are also cross-platform so you should be able to use poedit on windows and mac for editing and compiling MO files
You can import all the files to a single file and run that file
how do i do that?
im fairly new in this, so i dont know much
create another file and name it whatever you want and in it put
from foldername1 import main
from foldername2 import main
# and so on
But it's an unusual way of executing code though
What are you trying to do
Im making a discord auto message, i copy my friend code which are hardcoded into doing 1 message per
Idk how to make it so that i can send a message in multiple channel in 1 file
You'd probably have to use a loop
And for sending messages to a channel, a webhook would probably be more appropriate anywho
Tell your friend it will be much easier for both of you to use any api wrapper
Like discord.py, pycord, nextcord etc
I personally use pycord
I'd recommend making a webhook per channel you want to send, then you can just loop over a list of webhooks and post to them
Is there any tutorial i can look into, i have 0 clues how to do all that
Or maybe a template where i can learn from
The link at the bottom is the raw api if you want to call it yourself, but I do suggest you use a library
maximum number of choice with auto complete?
25
cool
anyone using on.render and uptimerobot to host their discord bots?
whats the best 24/7 free discord bot hosting
Free trials are available for Oracle or Digital Ocean. Free services are not recommended due to performance, security and stability issues
but they require identity or cc
i want totally fre
In that case, consider using your own computer haha
nah really bro pls i really want
Any service will ask you for a registration account for security reasons
Okay thank you!
you wont find that
thats like renting a house or apartment to someone for free
how do i run this file?
Just like how you run any other file?
are there bot commands alr made here?
#bot-commands
or is there any server that has commands
made for free use
Solar hosting
Bot host.net or discord bot host I forgot the name
Where can I learn discord py with image examples?
The number of times I've had people complain about this host is hilarious, also give their privacy policy a read sometime
There isn't a free lunch. People aren't going to spend their own money running your stuff
You got a point but some ppl are dumb too
I don't think they're dumb, they're malicious
If you can't identify the product being sold, you are the product being sold
Do you know any site for learning discord.py with image examples?
What images are you hoping to see? The library is just text
thanks
Like bdfd
Wait let me show you
the docs have image examples
Where do I find docs?
Specially for discord bots
Oh thxx
Is discord having API issues?
Welcome to Discord's home for real-time and historical data on system performance.
This is sometimes out of date ^
Yeah, it's updated when they notice it
in what way
Getting tons of timed out warnings in console
and my bots ping to discord is 200+
when its around 50
Discord is going to start having API issues starting soon, I am calling it. Happens a lot :(
i don't notice anything wrong
Then maybe its my vps.. but it just started now. So I am doubting its my vps. But time will tell ig
2024-08-05 17:35:16 WARNING discord.state Shard ID 0 timed out waiting for chunks for guild_id 110373943822540800.
does anyone know anything about interactions with buttons in discord.py and can help ?
Here's my code, my issue is that i'm not sure how to send a response to a button press interaction, i commented in the 3 places its relelvant
You're following a tutorial for another library, not discord.py
Also, in general I strongly recommend you don't nest class definitions inside of methods
huh?
import discord, random, json
from discord.ext import commands
from discord import app_commands
from discord.ui import Button, View, text_input
im not following a tutorial
but im using discord.py
Yes, but where are you starting from
You didn't divine the concept of a View from your mind
The only thing that's endorsed is the official docs and the examples in the repo
That tutorial was built on another library or likewise very misinformed
anyone can help me at #1270087125185986723 ive been waiting for quite some time
Can anybody help me code my bot for free since im a broke boi
pls dm me if you can help
I want to add the Help Section in my Discord Bot to the Discord Application Directory, but I am getting the pip error. It happens even though slash commands are installed. What can I do about this? I want it to work in my prefix
@bot.command(name='yardım')
async def help(ctx):
embed = discord.Embed(
title=":globe_with_meridians: Discord Bot Yardım Menüsü",
description="Aşağıdaki komutlarla botumuzdaki oyunları oynayabilirsiniz:",
color=discord.Color.blue()
)
embed.set_thumbnail(url="https://cdn.discordapp.com/attachments/1258806020982181969/1268934570200530944/cat-animal.png?ex=66ae3ae9&is=66ace969&hm=ef55b2e095888e0b9bfc8889ec9b4b0018f1c5b556ebb73901ec392a50e7a1ce&") # Replace with your image URL
embed.add_field(
name=":hammer: Taş Kağıt Makas",
value="**Komut**: `!tkm`\n**Açıklama**: Taş, kağıt veya makas seçerek bot ile karşı karşıya gelin. Botun seçimlerine karşı kazanmayı hedefleyin.",
inline=False
)
embed.add_field(
name=":coin: Yazı Tura",
value="**Komut**: `!yazıtura`\n**Açıklama**: Yazı veya tura tahmini yaparak paranın hangi yüzünün geleceğini tahmin edin.",
inline=False
)
embed.add_field(
name=":1234: Sayı Tahmin",
value="**Komut**: `!sayıtahmin`\n**Açıklama**: Botun belirlediği gizli sayıyı tahmin etmeye çalışın. Her tahmininizde bot size doğru olup olmadığını söyleyecek.",
inline=False
)
embed.add_field(
name=":x: Xox (Tic-Tac-Toe)",
value="**Komut**: `!xox`\n**Açıklama**: 3x3 bir tahtada X ve O'ları sırayla yerleştirerek üçlü bir sıra oluşturmaya çalışın.",
inline=False
)
embed.add_field(
name=":jigsaw: Bulmaca",
value="**Komut**: `!bulmaca`\n**Açıklama**: Size verilen ipuçlarını kullanarak bulmacayı çözmeye çalışın.",
inline=False
)
embed.add_field(
name=":kiss: Öp Evlen Öldür (Kiss-Marry-Kill)",
value=("**Komut**: `!kme`\n"
"**Açıklama**: Üç kişilik bir liste alacaksınız ve bu kişilerden birini öpecek, biriyle evlenecek ve birini öldüreceksiniz. "
"Seçimlerinizi yapın.\n"
"**Ek Komutlar**:\n"
"- `!balance`: Mevcut gem miktarınızı gösterir.\n"
"- `!mycharacters`: Evlendiğiniz ve öldürdüğünüz karakterleri gösterir."),
inline=False
)
embed.add_field(
name=":droplet: Su İçme Hatırlatması :droplet:",
value="**Komut**: `!suekle #kanal-adı`\n**Açıklama**: Her gün belirli aralıklar ile belirledeğiniz kanala su içmek için hatırlatıcı yolar.",
inline=False
)
embed.add_field(
name=":question: Yardım ve Destek",
value="Herhangi bir sorunuz olursa veya yardıma ihtiyacınız olursa, lütfen bir moderatöre başvurun. İyi oyunlar!",
inline=False
)
await ctx.send(embed=embed)```
What is the "pip error"?
are you using a virtual environment?
Don't use extra libraries, nextcord already has built-in application commands.
yeah
what Nightmare said though, try not to mix libs
A Python wrapper for the Discord API forked from discord.py - nextcord/nextcord
I installed nextcord later, I didn't have it, but it still gave me an error, I don't know how to do it.
thx
I'm new to this, what should I import or how did I code it exactly and what is my prefix? ! want it to stay what is
the bot prefix?
I want to use both the discord application directory and my own ! with prefix
check the nextcord repository and look at the examples, I don't use this library so I don't know what changes it has in detail
Thanks again
for this you just create the commands twice, once as prefix commands how you're used to, and once as app commands (which function fairly similarly, consult the docs but the API is similar for it)
we don't - and won't - support hybrid commands (prefix and slash with one decorator/function) because it means we have to substantially water down the API to just the commonalities between both systems, and it adds an extra layer of unnecessary complexity and abstraction we feel harms the lib more than it helps, if those are what you were looking for
is this a good way to be able to turn on/off any commands at any time i wish to?
speaking as a newbie
I would probably use Command.update() instead, and set enabled=False, and then catch that in an error handler. Then you don't need to add that check in every command that you have.
may I have an example? the site is trash and i dont understand anything from it
command = bot.get_command(name)
command.update(enabled=False)
then if a disabled command is being invoked, commands.DisabledCommand error will be raised
im sorry im this dumb, but could I also see a full example? like how it would get introduced in the following code:
@bot.command()
async def help(ctx):
await ctx.reply(f"{bot.user.name} is currently in development mode!", delete_after=6)
Do you edit this file manually?
um yes
idk any better, im not that good at managing/organizing stuff
no just asking
You could read the file when starting the bot, and then loop through the commands and disable the ones you want
i saw a friend of mine having a place where he can do something similiar to what I did so i got interested in doing it as well
nice
oh I see
I intiatially just wanted to have it like this at the start of the file:
help_CmdEnabled = True
@bot.command
async def help(ctx):
if help_Cmdenabled == True:
await ctx.reply(f'{but.user.name} is currently still in development mode!')
that works, but if you have a lot of commands, it can get messy pretty quick
Not only that but also the main.py file gets heavier
or actually, before I start any command, I can use that there, instead of the start of the file
like this maybe
@tired star your code worked great! however some words seem to not work?
like fr doesnt work but af does
ive tried putting .lower() but it doesnt work
Nvm found the issue
is there any event which is called when timeout is uplifted?
Hello how do i fix error code 429 : Too many request from [channelID]
I'm making a Discord auto message with a timer that sends message once every hour. The said channel has a cooldown of 1 hour.
on_member_update i think
compare the before.timed_out_until with after
Ok
Another question I would like to ask when someone is banned on_member_remove event is called?
should be
Oki
It's not getting called on when timeout expired only called when timeout is applied
xd
How to organise my code and bot slash commands into different files?
You can just declare things in other files and import them like normal python, bots are no different. You can also make use of the extension framework if you're using dpy
👍
Example code?
For?
For organizing code
I gave you two options
await user.timeout(timedelta(seconds=duration), reason=reason even if i putting duration 30 its still adding only 10 seconds
I personally think my teams code jam project looks pretty organised you can see the formatting https://github.com/Beardrop2/Zoomy-Zodiacs
Is it possible that it is getting reassigned ?
nope
@app_commands.command(name="timeout", description="Timeout a user")
@app_commands.describe(
user="The user to timeout",
duration="Duration in seconds",
reason="The reason for the timeout",
)
@app_commands.checks.dynamic_cooldown(cooldown_for_everyone_but_special_og)
async def timeout(
self,
interaction: discord.Interaction,
user: discord.Member,
duration: app_commands.Range[int, 2, 2073000],
reason: str,
):
await interaction.response.defer(ephemeral=True)
if not self.is_hierarchy_higher(interaction.user, user):
await interaction.followup.send(
f"Cannot timeout {user.mention} because they have an equal or higher role."
)
return
await user.timeout(timedelta(seconds=duration), reason=reason
yeh me and my friend is testing
i will try again
You may not want to reimplement this as there is a native timeout and you're reducing security controls
does anyone know about a template that isnt outdated for a discord dashboard i cant find any ones that work and are in python 😦
@glad cradle its pretty much a textual game centered on a eastern theme called cultivation
what are you using the files for?
storing user data
😭
?
why you're not using a proper database?
im stubborn
if you want a file like database there's Sqlite
im using pure pickle()
using files as database is very bad, it's also slower
what should i do then ;-;
Also you can and will randomly corrupt your file and lose everything
your file? or files?
try Sqlite
the files where you were performing operations
!pypi aiosqlite
yes, you need an async wrapper
alright
common file operations blocks the main event loop
normal functions dont right
depends on what you are doing inside them
!blocking
Imagine that you're coding a Discord bot and every time somebody uses a command, you need to get some information from a database. But there's a catch: the database servers are acting up today and take a whole 10 seconds to respond. If you do not use asynchronous methods, your whole bot will stop running until it gets a response from the database. How do you fix this? Asynchronous programming.
What is asynchronous programming?
An asynchronous program utilises the async and await keywords. An asynchronous program pauses what it's doing and does something else whilst it waits for some third-party service to complete whatever it's supposed to do. Any code within an async context manager or function marked with the await keyword indicates to Python, that whilst this operation is being completed, it can do something else. For example:
import discord
# Bunch of bot code
async def ping(ctx):
await ctx.send("Pong!")
What does the term "blocking" mean?
A blocking operation is wherever you do something without awaiting it. This tells Python that this step must be completed before it can do anything else. Common examples of blocking operations, as simple as they may seem, include: outputting text, adding two numbers and appending an item onto a list. Most common Python libraries have an asynchronous version available to use in asynchronous contexts.
async libraries
- The standard async library -
asyncio - Asynchronous web requests -
aiohttp - Talking to PostgreSQL asynchronously -
asyncpg - MongoDB interactions asynchronously -
motor - Check out this list for even more!
wait so like
if i use normal functions inside a async function its blocking
??? confus
shiiit
yes use this
i mean personally with small databases sqlite3 can barely be recognised for blocking the event loop
but its still a consideration, personally ive just used sqlite3 and there have been 0 problems its just as it gets bigger and bigger you will need to consider refactoring
how do you mean?
?
numbers?
yeah
sorry i joined half way through the conversation
storing numbrs with pretty much no worry of running out of space to represent the next one
no, as i said it depends on what you are doing inside them
i didnt mention this earlier
ah
math.
lots of it
what's really important is that you do not do web requests, heavy cpu bound work, and other things in non async contexts
check the computational time it takes for the computer to process your function then decide if you need to implement it to be async
aka requests -> aiohttp
yeah but you could also wrap requests methods with some asyncio methods, so not necessarily
but doesnt the request method require to be async (internally) 0? thats the point of the aiohttp package
last time i checked those dunder functions can be like
1 to 0.1 ms
asyncio provides some methods to safely run blocking functions as async, without blocking the event loop
then its not a concern
alright
"lots of math" we reference is like 5-10 seconds long of billions of numbers
oh
but less than a ms doesnt really impede your event loop
my library will flop trying to do more than 10k numbers
may need to refine it, can i ask what you are handling numbers for?
what is really an issue are operations that makes you wait a lot of time, for example when you do a web request you must wait the server response, that response could take seconds and if not done in an async context you lose that seconds waiting for the response, same thing when you work with files locally but you instead wait for the kernel and other signals
just the numbers in general, what are they representing
i dont think ill do web request stuff
big numbers..?
the class is literially called BigNumber
whats the numbers for haha?
to represent absurdly massive numbers?
so you have a class to just make big numbers end of ??
so confused, the numbers have no meaning nothing, just a big number?
it can represent 10^^4 with alot of extra wiggle room
fair enough
they mean something
thats what they represent
a mantissa and exponent
i dont even know if ill be able to rewrite it in C xd
my win machine is absurdly cursed
anyway i guess ill go back to the main python channel
just wanted to give you a general idea, it's not important the total execution time of a function, it's important if you are waiting a lot of time without doing anything, CPU bound operations give you no gain if you make them async, they're slow in python and what's slow are the operations itself, you could make them in another thread (just an example)
so if you wait a lot of time for something without doing anything you should make that thing async
Can someone help me script my discord bot for free since im a brokie
DM me if you can
I send form when someone click on a button i want when someone submits the form the embed on which button is there should stop listening , currently even after removing and submitting the form and editing the embed ,embed timeout still get fired
what discord lib?
Embeds don't listen to anything though?
import requests
import json
TOKEN = ""
APPLICATION_ID = ""
GUILD_ID = ""
def register_command():
response = requests.post(
url=f"https://discord.com/api/v10/applications/{APPLICATION_ID}/guilds/{GUILD_ID}/commands",
headers={
"Authorization": f"Bot {TOKEN}",
"Content-Type": "application/json",
"User-Agent": "Mozilla/5.0",
},
data=json.dumps({
"name": "hello",
"description": "Hello, world!",
})
)
if response.status_code == 201:
print("Command registration successful.")
else:
print(f"Error registering command: {response.text}")
register_command()
Error registering command: {"message": "internal network error", "code": 40333}
What's wrong with this code? All parameters are precisely specified
Why are you setting a User-Agent? And what's the end goal here, what is actually serving those commands?
I meant button😅
Btw i have solved the issue by passing the same instance to the form
And disabling on submit
I have a query suppose i have all the commands copied to the guild only
If someone dms the bot ,will it log the messages on on_message.
Can someone help me on a error message I'm getting on one of my commands?
If you're subscribed to the right intent, yes dm's will fire on_message
Only if you send the error message 😉
let me see if I get it
Oki another query I have suppose my lower hierarchy role has perms of send message but my higher don't
Which role will take priority if i have both?
The Channel Overrides section goes into this in detail
File "/data/data/com.termux/files/home/cmds.py", line 132, in shift_leaderboard
await interaction.response.send_message(embed=embed, view=view, ephemeral=True)
File "/data/data/com.termux/files/usr/lib/python3.11/site-packages/discord/interactions.py", line 855, in send_message
await adapter.create_interaction_response(
File "/data/data/com.termux/files/usr/lib/python3.11/site-packages/discord/webhook/async_.py", line 221, in request
raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction
does the command still look like it works?
So hierarchy don't matter hmm 🤔
Idk, when its executed it says application didn't respond or sum like that
That is most likely because you are taking to long to respond. You get 3 seconds. To extend this time to 15 minutes you can defer right at the beginning of your callback
I'll fix that, thanks
No documentation found for the requested symbol.
That is not in discord.py you will have to go to the pycord docs (to the person who ran the command above)
I’m trying to set a description that shows when the [number] is clicked
how do you make your options (can you show your code)
but I keep getting an error that tells me bridgeOption will be removed on 2.7 update
1 sec
Yes bridgeOption is deprecated. I think you can just use normal options now let me check.
Edit: You need to use BridgeOption using Option is deprecated
I have deleted the code from my project due to the same error which you said, will try to find it and send a ss
so the problem is this my server have onboarding feature enabled and for creating mute feature i need to disable send_message from everyone role so is there any hack which can fix it?
by hack i mean the way
plz dont misunderstand it
You can replace bridge options with the bridge_option decorator
or just use discord.Option but that might change in 2.7 again
Edit: I mixed it up
hey can anyone help me with this embed inline im trying to make the add_field for 2 each sections like the 2 below which im trying to do for all like 2 for each sections - my code
embed = discord.Embed(title="Stats", color=discord.Colour.dark_theme())
embed.add_field(name="Data", value=f"`{Data}`", inline=True)
embed.add_field(name="Total", value=f"`{Total}`", inline=False)
embed.add_field(name="Jale", value=f"`{Jale}`", inline=True)
embed.add_field(name="Lum", value=f"`{Lum}`", inline=False)
embed.add_field(name="Aa", value=f"`{Aa}`", inline=True)
embed.add_field(name="Number", value=f"`{Number}`", inline=True)
may you check your dms please
Try switching the 2nd field to True
3rd to false
4th to true
5th to false
When inline is false it buts that field on a newline
Extensions are extra utilities that are in discord.py
Think of it like default libraries for python
You can do import math in python to get extra features and you can do from discord.ext import commands to get extra features in discord.py
Cogs are a way to group your commands (and other code) and allow you to split your bot into multiple files much easier. Cogs have a few extra utility features such as being able to apply changed code in the cog without restarting the whole bot.
I see, thank you for your explanation, and one more thing about the recent update on discord.py for user-installable apps, the docs is quite unclear on how it works, do you have any information related to it?
You can make a role and than in every channel create an override for that role that disallows sending messages. Or you can also use the built in discord timeout feature which also would disallow other things and has an automatic timeout
Sorry no. I do not know how discord.py implemented user apps. I only use py-cord. (I just know some of the basics of d.py as py-cord is a fork of it)
^
I see, thank you for your help though!
timeout is broken rn
How so?
see inspite of being timeout the user can send message
is it gonna be fine to make a function that will send an embed that isnt defined as an async one but is still called in a async function
@app_commands.command(name="timeout", description="Timeout a user")
@app_commands.describe(
user="The user to timeout",
duration="Duration in seconds",
reason="The reason for the timeout",
)
@app_commands.checks.dynamic_cooldown(cooldown_for_everyone_but_special_og)
async def timeout(
self,
interaction: discord.Interaction,
user: discord.Member,
duration: app_commands.Range[int, 2, 2073000],
reason: str,
):
await interaction.response.defer(ephemeral=True)
if not self.is_hierarchy_higher(interaction.user, user):
await interaction.followup.send(
f"Cannot timeout {user.mention} because they have an equal or higher role."
)
return
await user.timeout(timedelta(seconds=duration), reason=reason
)
embed = self.build_embed(
"timeout", user, interaction.user, reason, duration)
await interaction.followup.send(
f"{user.mention} has been timed out for {duration} seconds. Reason: {reason}"
)
await interaction.guild.get_channel(ChannelsIds.TIMEOUT).send(embed=embed)
this is my command code
if u test on different device u will get different timeout
It looks right to me ¯_(ツ)_/¯
u can return embed from function and then send it
yeh its a bug from discord side
ah okay
Why can it not be async?
idk
idk how async functions work
like does the function wait for it to be done
i kinda need it to block the rest of the function
Generally it is best to keep everything in an async function async but I am not the most knowledgeable on it either
alright
i usually do if i have to do api calls which can block the bot execution i put them in async if its just a simple embed building then i just use sync
Hi im still not getting what i wanted here is the pic when i put ur code in
embed = discord.Embed(title="Stats", color=discord.Colour.dark_theme())
embed.add_field(name="Data", value=f"`{Data}`", inline=True)
embed.add_field(name="Total", value=f"`{Total}`", inline=True)
embed.add_field(name="Jale", value=f"`{Jale}`", inline=False)
embed.add_field(name="Lum", value=f"`{Lum}`", inline=True)
embed.add_field(name="Aa", value=f"`{Aa}`", inline=False)
embed.add_field(name="Number", value=f"`{Number}`", inline=True)```
Hmmm, inline is always so strange. I have to go but you could just flip a few values here and there and see what happens
Ok
little confused about all of this subclass stuff
do you really need a python subclass?
You'll need to add an empty third field for that
for buttons*
Since it's max three on one line and it depends on the display size
# field 1
# field 2
# empty field 3 (namw="", value="")
# field 1
# field 2
...
inline defaults to True btw
yes, subclassing inherits functionalities of the class so if you wanna override its method you would do that.
oh
Oh alright thanks!
It is important to know OOP before making a Discord bot, consider practicing with some exercises and understanding how classes and subclasses, etc. work.
im fine with normal classes
subclasses on the other hand
also i already made the discord bot
im just fleshing it out
Ok, but it is not necessary to create a subclass for a button, if the button has a simple function you can create it directly
i wish to make buttons with a simple function :>
What library do you use?
I'm not sure if buttons in discord.py are the same as py-cord 😅
lol
what's your question about buttons?
should be possible to forgo the subclass right?
In py-cord it can be done this way, in discord.py in the documentation I see that it should be the same, you can try:
import discord
from discord.ui import Button, View
async def button_callback(interaction: discord.Interaction):
await interaction.response.send_message("You pressed the button!", ephemeral=True)
# Create the button
button = Button(label="Click me", style=discord.ButtonStyle.primary)
button.callback = button_callback
# Create a view and add the button to it
view = View()
view.add_item(button)
# Example of how to use the button in a command
@bot.command()
async def show_button(ctx):
await ctx.send("Here's a button for you:", view=view)
you can do this in d.py too
Note: It is not highly recommended to create buttons or other components in this way, but if your button is simple you can do it
Oh ok
i do alot of HOF
huh
thats the code stripped down?
can i wrap it into a class
yeah, by subclassing
confus
if you don't subclass you don't have much reason to put it into a class
you can just do that when you need the component, directly inside the command callback
i just need the command callbacks to perhaps return a value
import discord
from discord.ui import Button, View
async def button_callback(interaction: discord.Interaction, text= str, passedFunction = None, input1, input2):
await interaction.response.send_message(text, ephemeral=True)
if passedFunction != None: return(passedFunction(input1, input2))
# Create the button
button = Button(label="Click me", style=discord.ButtonStyle.primary)
button.callback = button_callback(button, "click me", specialFunction, placeholder1, placeholder2)
# Create a view and add the button to it
view = View()
view.add_item(button)
# Example of how to use the button in a command
@bot.command()
async def show_button(ctx):
await ctx.send("Here's a button for you:", view=view) ```
@glad cradle ?
can i do this bizzare stuff
you can't change the callback in that way
if you want to hold state you need to put that into the view or into the button
why don't you read a guide about OOP? it's really powerful if you learn it
im stubborn
i am already locked into a state of knowing OOP
its just that this OOP is foreign to me :>
wdym? you just asked about inheritance the other hour
shhh
i dont remember anything earlier fr
python is based on that, you will need it for other things too
i have like 5 classes already ;-;
nothing wrong with classes
It is better if you make a subclass, it allows you to add more functions and is also more organized
wait this is so simple wth
# Define a simple View that gives us a confirmation menu
class Confirm(discord.ui.View):
def __init__(self):
super().__init__()
self.value = None
# When the confirm button is pressed, set the inner value to `True` and
# stop the View from listening to more input.
# We also send the user an ephemeral message that we're confirming their choice.
@discord.ui.button(label='Confirm', style=discord.ButtonStyle.green)
async def confirm(self, interaction: discord.Interaction, button: discord.ui.Button):
await interaction.response.send_message('Confirming', ephemeral=True)
self.value = True
self.stop()
# This one is similar to the confirmation button except sets the inner value to `False`
@discord.ui.button(label='Cancel', style=discord.ButtonStyle.grey)
async def cancel(self, interaction: discord.Interaction, button: discord.ui.Button):
await interaction.response.send_message('Cancelling', ephemeral=True)
self.value = False
self.stop()```
super() is cogs thingy right
no that's a python OOP concept
in fact you can see super in other languages as well
any OOP learning enjoyers in chat
in simple term, super() refers to your parent's, in this case, calling the constructor
so it refers to discord.ui.View ?
so
a
subclass() is the child of its class()
and reversed
class() is the parent of its subclass()
yes
super() returns the subclass() parent which is its class()
alright thank u
oh wait
confus brain lool
Yes
idk if what this code does but does it add a button?
@discord.ui.button(label='Confirm', style=discord.ButtonStyle.grey)
async def doButton(self, interaction: discord.Interaction, button: discord.ui.Button):
await interaction.response.send_message('Confirming', ephemeral=True)
result = self.func(attr1, attr2, attr3):
if self.returnVal:
self.returned = result
self.stop()
Not only buttons, it can also be combined, menus and buttons for example
i cant even tell lol
actually i guess it does
anyone know how to get it into the center, im not the one coding this but the guy who is, is offline so im just fixing this, heres some of the code to do with the position
base_image = base_image.resize((2479, 1080))
overlay_image = overlay_image.resize((500, 500))
if overlay_image.mode != 'RGBA':
overlay_image = overlay_image.convert('RGBA')
position = (100, 100)
new_image = Image.new('RGBA', base_image.size)
new_image.paste(base_image, (0, 0))
new_image.paste(overlay_image, position, overlay_image)
(i have never used python before)
There are 2 ways to create components, using decorators inside a class that inherits from View or creating a subclass and adding it to the view
what does a component mean, or components
Buttons or menus
oh im dumb
big confus fr
also
@discord.ui.button(label='Confirm', style=discord.ButtonStyle.grey)
async def doButton(self, interaction: discord.Interaction, button: discord.ui.Button):```
this part is the one responsible for making the "component" yeah?
That decorates a method to make it into a component (button)
Yes, it's confusing sometimes.
so if i do the class like
view_or_component = discordButton(##args)
cause im pretty sure it returns a view
What is discordButton?
class discordButton(discord.ui.View):
def __init__(self, func, attr1= None, attr2= None, attr3 = None, returnVal: bool = False, ):
super().__init__()
self.func = func
self.attr1 = attr1
self.attr2 = attr2
self.attr3 = attr3
self.returnVal = returnVal
self.returned = None
@discord.ui.button(label='Confirm', style=discord.ButtonStyle.grey)
async def doButton(self, interaction: discord.Interaction, button: discord.ui.Button):
await interaction.response.send_message('Confirming', ephemeral=True)
result = self.func(attr1, attr2, attr3):
if self.returnVal:
self.returned = result
self.stop()
ignore the comments ( i copied that code )
so this will make a view with a single component which is.. a single button yea?
Well, despite the class being named "button" that would indeed give you an object that subclasses view
Correct
this server is great help
i think your in the wrong channel tho
You asked a question that isn't on topic for this channel 
its for a discord bot
so what should i do if i want to add more buttons later on
yea but i think that stuff doesnt have anything to do with discord bots
This isn't a channel for all possible things one could wrap with a bot
what channel then
idk go ask for help in #python-discussion first
ok
Just more methods with that decorator
As long as the method is named uniquely in the class
i call the method? or do i add more methods?
cause i wish for the 1st option to be done
More buttons = more method declarations
hm
Each method is one button, and the body of the method is what happens when that specific button gets pushed
Huh? What are you trying to accomplish?
When you say "add buttons later on", do you mean you the developer adding features or the view dynamically changing during runtime?
ok so like
imagine this
view = makeview(## args for the first button)
view = view.addbutton(## args for the second button)
view = view.addbutton(## args for the third button)
## done until u got what u needed
Hm. What are the cases where the buttons on the view would change?
Or are there the same X buttons every time?
for context i wanna use buttons for like
zones
Or is this like "I make the view and I have an int N and I want to make N buttons at that time"
For that, instead of using the decorators like above, you can instead make a subclass of discord.ui.Button
subclasses galore 💀
ok i guess i gotta ask chatgpt to help me
Similarly to how to subclass a View, you can also subclass a Button or other components like Select menus.
Adding the item to the view
To add a subclassed item to your view, simply call View.add_item on your view, passing an instance of your subclassed item.
Button Example
class CounterButton(discord.ui.Button):
def __init__(self, label='0', **kwargs):
super().__init__(label=label, **kwargs)
self.counter = 0
async def callback(self, interaction: discord.Interaction):
self.counter += 1
self.label = self.counter
await interaction.response.edit_message(view=self.view)
view = discord.ui.View()
view.add_item(CounterButton(style=discord.ButtonStyle.primary))
view.add_item(CounterButton(style=discord.ButtonStyle.success))
view.add_item(CounterButton(style=discord.ButtonStyle.danger))
await ctx.send('Click counter button below', view=view)
(From a user tag on the dpy server)
The key thing is that in addition to the @ui.button decorator, you can also just make Button objects on your own with their own callback. This lets you dynamically make however many of whatever type you want
ooh
now i put whatever i want to happen in the callback function yes?
Exactly
is it possible to pair this with the view subclass
Absolutely and it's recommended
or do i need to
Your view subclass's init can create your buttons (using the button subclass) and add them to itself
hear me out on what i want my code to do
class MyView(View):
def __init__(self):
super().__init__()
self.add_item(MyButton())
ok so i got an embed it shows some possible zones, this part is frontend and got nothing to do actually
then i wanna make a view, add a few buttons depending on the zones that the user can go to
if they click on one button, all the other buttons disappear
sorry for the ping but i want your opinion on the above
Ah yup this seems like you'd want what I described
The button can also internally modify the view (remove other buttons) and then edit the message to reflect that change
so basically
buttonsubclass() - to make buttons
viewsubclass() - yeetus deletus buttons, and manage them
So something like
class ZoneButton(ui.Button):
def __init__(self, whatever):
super().__init__()
self.whatever = whatever
async def callback(self, interaction):
#can use self.whatever, do logic
await interaction.response.edit_message(view=None) # gets rid of all buttons
basically
If the button callback needs to mess with the view it's in, you can use self.view
self is the ui button?
class ZoneView(View):
def __init__(self, zone_list):
super().__init__()
for zone in zone_list:
self.add_item(ZoneButton(zone))
In the context of the button subclass, yes
self is the instance of the class you're declaring
how considerate of whoever made this hell hole of classes fine ballet of classes and functions
It takes a lot of mental reprogramming to think in terms of classes and objects after just doing declarative scripting, but they're incredibly powerful
the most OOP ive done before this was in the form of pygame and my own number library
if u want to see the hell here https://paste.pythondiscord.com/DISA xd
Oh wow
btw for this example it needs **kwargs what if i want my own keyword arguements in this
Oh your subclass can take in whatever parameters you want, or it can just pass defaults to the parent constructor. Completely up to you. **kwargs just helps if you want the consuming code of your subclass to also be able to declare base view parameters (like timeout)
Looks really comprehensive, what's the game for?
wdym game for?
i mean im not currently working on the game but
its meant to reach absurd numbers
Oh like things that would normally overflow
will **kwargs take in any kwargs of my own?
like what happens if i
def __init__(self, label: str = "", **kwargs, destructAll: bool = False, ):
super().__init__(label= label, **kwargs)
self.destructAll = randomkwarg
i guess i should search for what it is
oh i see
**kwargs would go at the end yeah and just be a catch all for any other flags they'd pass in
yeah i thought so
The docs will tell you what the base class accepts, and it's up to you if/how you pass that into super().__init__(). You can just pass in hard coded things, or accept them in your own init
class discordView(discord.ui.View):
def __init__(self):
super().__init__()
self.returned = None
class mkButton(discord.ui.Button):
def __init__(self, label: str = "", func, attr1= None, attr2= None, attr3 = None, returnVal: bool = False, destructAll: bool = False, **kwargs ):
super().__init__(label= label, **kwargs)
self.destructAll = destructAll
self.func = func
self.attr1 = attr1
self.attr2 = attr2
self.attr3 = attr3
self.returnVal = returnVal
async def callback(self, interaction: discord.Interaction):
result = self.func(self.attr1, self.attr2, self.attr3):
if self.returnVal:
self.view.returned = result
if self.destructAll:
await interaction.response.edit_message(view=None)
self.view.stop()
oh wait
waddya' think?
Seems solid, though the view doesn't do anything or add any components
it keeps self.returned tho
Right, but it doesn't have any components. Unless something outside of this is adding components to it
You could do that and it would work. I recommend you put that all in the view subclass so it internally is clear how it works
adding it myself is the amount of control i want
hm
what about inheritance
What would be inheriting what? You could actually make an intermediate level, people often do this to centrally declare like error handling across multiple views
Then you can put the add_item's wherever, it's just much clearer and encapsulated if you do that in the view class itself
Like this
wait how do i send a view
the view= parameter of pretty much any method that sends a message
i got
msg = await ctx.send(embed=Embed)
for embeds
so can i do
await ctx.send(view= view)
oh
yup
good to know
by the way
lets say i got a functin yea
how do i ignore certain arguements
How do you mean?
explicitly coded in params part of defining a function
like
def func(arg, ignore ignore):
this
attr1,attr2,attr3 will get shoved into func regardless if the function likes it or not
You're declaring those parameters though, do you not want the user to pass them in?
Then you would accept those in those functions
Right, so accept the parameters you want in those functions
any way to do them cleanly?
Or is this like futureproofing that you may want additional things on the view itself in the future?
You can just add them in when you need them
If you wanted this very very flexible, you could accept a dictionary or just **kwargs
but that makes the api less straightforward about what you're asking for
i finally got it to work without crying at me
wait hold on
it cried a little
it worked
i sent a img in dms
ty man
Please which is the best library to build a social media bot for account management
What does "account management" mean?
what's the context
Everyone asks "what" but never "how is" 
what kind of coding is that 😭
For scheduling what you guys use? I have a discord giveaway command but don't know how to schedule,can't use task as it will be fixed on bot start up
What do you mean?
It is python. Specifically for a event in a discord bot
You can create tasks dynamically iirc
How?
If its possible then it will solve my problem
you can create an instance of ext.tasks.Loop and set a callback
I believe the first argument coro is the callback function
I am really
on this I need to try this thing out
Store thing in database -> on startup read from database -> spin up however many asyncio tasks you want that sleep until the time you want and then do the thing
hi does someone know how to work with oauth ?
@gray terrace
any one know how to fix Windows Subsystem for Linux has no installed distributions.
Use 'wsl.exe --list --online' to list available distributions
and 'wsl.exe --install <Distro>' to install.
Distributions can also be installed by visiting the Microsoft Store:
https://aka.ms/wslstore
Error code: Wsl/Service/CreateInstance/GetDefaultDistro/WSL_E_DEFAULT_DISTRO_NOT_FOUND
this error?
wrong channel for that
where do i go?
what channel would it be because its discord bot related cuz hes trying to use the mongodb db
Probably not in scope of this server as it's not python related at all
Looks like you just need to do the commands in the message
it might be acceptable under #tools-and-devops too, but that error has only been mentioned once before in this server apparently, you'll likely find more details searching it on the internet
https://github.com/microsoft/WSL/issues/9338
How do I check a member that's pinged through a message?
Like if I send '.punch @brazen wind' it'll respond with '@brazen wind has been punched'
@bot.tree.command(name="edit", description="Edit the message content for a specified channel.")
@app_commands.describe(channel_id="The ID of the channel to edit the message content for.")
async def edit(interaction: discord.Interaction, channel_id: str):
await interaction.response.send_message(f"Please provide the new message content for channel {channel_id}.")
def check(m):
return m.author == interaction.user and m.channel == interaction.channel
try:
message = await bot.wait_for('message', check=check, timeout=120)
if message.content: # Check if the message content is not None or empty
file_path = await get_channel_file_path(channel_id)
with open(file_path, "w") as f:
f.write(message.content)
await interaction.followup.send(f"Updated message content for channel {channel_id}: {message.content}")
else:
await interaction.followup.send("Received empty message content. Please try again.")
except asyncio.TimeoutError:
await interaction.followup.send("You took too long to respond. Please try again.")
can anyone tell me why whenever i say something it still keeps responding with received empty message?
You can use the on_message() event and check if the message contains mentions
how could I get the mentioned user afterwards
Do you want the message to appear after the mention? or what do you mean?
sort of like if I do !greet @user the bot will say "hello, @user!"
A command can do that, is simple
is it possible to do it without a slash command
yes
can you help me with how 😭
Example:
from discord.ext import commands
from discord import Member
bot = commands.Bot(...)
@bot.command(name="greet")
async def example(ctx: commands.Context, user: Member):
await ctx.send(f"Hello! {user.mention}")
Do you have the Message content intent?
Hmm is there a way to have a bot remember context via a reply? I am using the discord.py right now
Maybe you're looking for a FSM (Finite State Machine) or something similar? I don't think discordpy has them out of the box, but maybe there are some 3rd party libraries
Uhhh I don’t really know 😅. I’d want it to be like
Bot; Spews out info”
Me: Replies with follow up question
Bot: answers with context of previous answer
Hmmm, you can use the on_message() event and put a condition that checks that the user responded to the bot's message
C:\Users\Games\AppData\Local\Programs\Python\Python311\python.exe
Traceback (most recent call last):
File "d:\Documents\Downloads\discord spotify.py", line 6, in <module>
import yt_dlp as youtube_dl
ModuleNotFoundError: No module named 'yt_dlp'
PS C:\Users\Games>
hey so i did install the module named yt_dlp but it still says no module name yt_dlp
Can someone help me with this 😭
I’m so confused what I’m missing because the bot is sending the message / running just fine, it’s just not detecting any real user’s status and just its own status
make sure you have installed it in the same env as the one you are running your project with
(And if you're using yt_dlp that you aren't violating dev terms of service)
how do i check what modules i have installed?
iirc pip freeze
Just pip on its own can be ambiguous if you have multiple python installations, especially on windows
<your python exe> -m pip freeze will specifically give you the packages in that environment
(Unless you're in an active venv then it's fine)
how long can be a button label?
80 chars
took me 10 seconds to find in the documentation
https://discord.com/developers/docs/interactions/message-components#button-object-button-structure
tnx
where should i intialize my db connection? on setup hook only?
i create it just in the script so outside of any hooks and then add it as a "variable" to the bot
so i can just do bot.db everywhere
cause u only need to do it once, i just do it when the bot is run
setup hook works
oki
yeah i am also planning to attach it to bot instance so only one connection is used across the file
what db are u using?
which db connector do you use,
dont use a single connection if possible
use a pool
i do like aiomysql
i am using asyncpg
and yes i am using pool
async def connect(self):
try:
self.pool = await asyncpg.create_pool(dsn=self.dsn)
log_message(log_level="INFO",
message="DATABASE Successfully connected")
except Exception as e:
log_message(log_level="WARNING",
message=f'Failed to connect to the database: {e}')
self.pool = None
heyo idk how to fix this yet pls help
import discord
from discord.ext import commands
import config
from main import colors
class Information(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.hybrid_command(name="userinfo", aliases=["whois"], description="Display information about a user.")
async def userinfo(self, ctx: commands.Context, user: discord.User = None):
if user is None:
user = ctx.author
public_flags = {
'staff': '',
'partner': ':partner:',
'hypesquad': '',
'bug_hunter_level_1': '',
'house_bravery': '',
'house_brilliance': '',
'house_balance': '',
'early_supporter': ':earlysupporter:',
'team_user': ':team_user:',
'bug_hunter_level_2': ':bughunter_level_2:',
'verified_bot': '',
'early_verified_bot_developer': '',
'certified_moderator': ''
}
badges = [emoji for flag, emoji in public_flags.items() if getattr(user.public_flags, flag)]
badges_str = " ".join(badges) if badges else "No badges"
avatar_link = f"[Avatar]({user.avatar.url})" if user.avatar else "Avatar"
banner_link = f"[Banner]({user.banner.url})" if user.banner else "Banner"
profile_links = f"{avatar_link} ∙ {banner_link}" if user.banner else avatar_link
created_at = user.created_at
created_str = f"{discord.utils.format_dt(created_at, style='R')}"
created_value = created_at.strftime("%m/%d/%Y") if (discord.utils.utcnow() - created_at).days < 365 else f"{int((discord.utils.utcnow() - created_at).days / 365)} years ago"
mutual_guilds = len([guild for guild in self.bot.guilds if guild.get_member(user.id)])
embed = discord.Embed(
color=colors.default
)
embed.set_author(name=f"{user} ({user.id})")
embed.set_thumbnail(url=user.avatar.url if user.avatar else None)
embed.description = badges_str
embed.add_field(name="Created", value=created_value, inline=True)
embed.add_field(name="Profile", value=profile_links, inline=True)
footer_text = f"Mutual servers: {mutual_guilds}"
embed.set_footer(text=footer_text)
await ctx.send(embed=embed)
async def setup(bot):
await bot.add_cog(Information(bot))
Hard to without knowing what's happening and what isn't working
the entire command 
...
what is happening, and what do you want to happen, and how do those things differ
…
no error in console and to work?
What are you physically doing, on your keyboard, and what do you see on your screen
your discord message?
Is your bot running? What are you doing after you run your bot, and what happens?
bot runs, just this one userinfo command doesnt work, just doesn’t respond
When you say "doesn't work", again, what are you doing, and what happens
Are you typing something into discord? If so, what and where?
are u just executing the command and it shows you thinking or no response. or does the whole command not show up?
a detailed description of what you do and what happens is needed or nobody will be able to help
no response
that’s a goood response for someone who doesnt speak english wym
have you tried putting the interaction as a parameter in your method header? because then you can defer the interaction and do a follow up with the embed
it either does not reply to the context properly at the moment or takes longer than 3 seconds, which is the timeout duration for interactions if you dont defer them
any command you run, creates an interaction object, which u can get by replacing your whole ctx param with interaction: discord.Interaction (i think)
there you can do interaction.defer to get 15 minutes instead of 3 seconds to reply, and then do a followup with your embed
u using discord.py`?
When you say "no response", what are you doing
Are you typing a prefix command? If so, where? Are you executing a slash command?
yes
hybrid commands are prefixed + slash commands.
:incoming_envelope: :ok_hand: applied timeout to @proud mulch until <t:1723135323:f> (10 minutes) (reason: duplicates spam - sent 4 duplicate messages).
The <@&831776746206265384> have been alerted for review.
word.
whats the thing to find info on public_flags?
!d discord.User.public_flags
property public_flags```
The publicly available flags the user has.
how to add this badge to my userinfo command? only hype squad badges seem to work
Did u read it lol
Mb
There is no way to definitively tell if someone has nitro. You can guess based on if they use nitro features, but the api doesn't tell you
is that a work around?
OMG UR PROFILE IS SAURRR PRETTY
omggg i got ittt nowww thankkk youuuuu
u can check it if you perform oauth with identify scope
there is a premium type flag somewhere iirc
too much work, i just checked if user has a banner 
im smart innit
You're going to get false negatives no matter what you do
pls elaborate?
The API does not tell you when someone has nitro
you are guessing. You are going to be wrong
<3
False negative means you say someone doesn't have nitro when they actually do
oh
bruh
a person can have nitro
BUT NO BANNER set up

bruh I thought there was a property for nitro in discord.py
smth like premium_since or smth.
that can be None if they do not have nitro.
or is that for server boosting? idek atm.
That is just server boosting yes
dk what else to do gang
people dont consider nitro basic nitro anyway
wrong, basic is still nitro
anything above paying 0$ to discord for nitro is still nitro lol.
Uh I need help with my bot
What's the problem?
word
how would i go about getting a users profile theme? like there primary and accent?
errr @fast osprey 🥺
you cant
i think you can get their banner though (if they have one)
so it seems impossible to read an asset after it got deleted, is there any way to find it?
can someone help me with my bot? dm me im on dnd
odd, can you make your bot hidden?
like hidden from the server list?
because I added my bot to my server but I don't see it in the member list but can use commands and stuff
That seems more like a discord quirk. Like discord has not updated your bots online status or something.
If your bot only uses http interactions and not the gateway it will also not appear to be online.
Also it could be due to the bots permission not being allowed certain things in a channel. As discord only shows members with some set of permissions in the member list. I think it is the send message permission and this will update per channel depending on permissions
ohh, yeah. thx
[2024-08-08 14:35:02,390] [ERROR [523] Ignoring exception in on_member_join
Traceback (most recent call last):
File "/usr/local/lib/python3.11/dist-packages/discord/client.py", line 449, in _run_event
await coro(*args, **kwargs)
File "/root/unibot/cogs/workers/welcome_leave_handler.py", line 76, in on_member_join
await member.add_roles(join_role)
File "/usr/local/lib/python3.11/dist-packages/discord/member.py", line 1083, in add_roles
await req(guild_id, user_id, role.id, reason=reason)
File "/usr/local/lib/python3.11/dist-packages/discord/http.py", line 754, in request
raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10007): Unknown Member```
Tf does that mean?
How are they Unknown when they just joined?
How tf is this even possible dog? In what world in dpy?
How can a member join then just be like "oh they aren't found uh oh lets throw an error 🤖"
It couldn't cache the member probably
Or they immediately left after joining maybe
Goofy, go to dms rq
I got a question
How the heck is it going thru both if statements?
When they are clearly different 
@stark ingot Your name says ping when responding

clear else statement

C:\Users\luffy\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\cog.py:796: RuntimeWarning: coroutine 'setup' was never awaited
setup(self)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
Loaded cog: test
Logged in as default (1265842230762016798)
------
Ignoring exception in command None:
discord.ext.commands.errors.CommandNotFound: Command "ping" is not found```
can someone help me?
what library and version are you using?
id expect that error from using discord.py 1.7.3 or pycord
and the version?
pip show discord.py or pip list should tell you
err that package you shouldnt have
if its for a self bot we can't help with that
