#discord-bots
1 messages Β· Page 182 of 1
I don't know why it doesn't work but I would advise you to change your on_message and instead do a @client.command
ok lemme try that
import commands form discord.ext
how do i do that?
and the third line to py client = commands.Bot(command_prefix"your_bot_prefix, intents=discord.Intents.all())
and then i need to edit the rest?
is the code from chatgpt?
ofc
ask him to change the code with a command instead of a on_message event
and try to understand btw
lol
ye
import discord
from discord.ext import commands
import mysql.connector
client = commands.Bot(command_prefix=">",intents=discord.Intents.all())
TOKEN = 'your_bot_token'
CHANNEL_ID = 'your_channel_id'
cnx = mysql.connector.connect(
host="your_host",
user="your_user",
password="your_password",
database="your_database"
)
@client.command
async def register(ctx):
accountname = message.content.split(" ")[1]
discordid = message.author.id
cursor = cnx.cursor()
query = f"UPDATE account SET reg_mail = '{discordid}' WHERE username LIKE '%{accountname}%'"
cursor.execute(query)
cnx.commit()
cursor.close()
await message.channel.send(f"{accountname}'s account has been updated successfully!")
client.run(TOKEN)
indents are wrong bcz im on mobile
so rename this? to !register?
kk
i forgot () after client.command
@client.command()```
Traceback (most recent call last):
File "/usr/local/lib/python3.8/dist-packages/discord/ext/commands/core.py", line 229, in wrapped
ret = await coro(*args, **kwargs)
File "register.py", line 21, in register
accountname = message.content.split(" ")[1]
NameError: name 'message' is not defined
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/usr/local/lib/python3.8/dist-packages/discord/ext/commands/bot.py", line 1349, in invoke
await ctx.command.invoke(ctx)
File "/usr/local/lib/python3.8/dist-packages/discord/ext/commands/core.py", line 1023, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
File "/usr/local/lib/python3.8/dist-packages/discord/ext/commands/core.py", line 238, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: NameError: name 'message' is not defined
@client.command is definitely the way forward
@slate swan i fixed it with chatgpt
ty for your help
Traceback (most recent call last):
File "C:\Users\hackt\Desktop\desktop\Exile\main.py", line 4, in <module>
from views.contact import Confirm
ModuleNotFoundError: No module named 'views.contact'; 'views' is not a package```
**HELP**, GIVING NITRO IF FIX
hey people, aiosqlite works with a database file right?
It seems your module has a error
There is no package named "views" and hence no module named "contact"
Are you trying to import a library or are you trying to import a package from your pc? @tawny mantle
dm @twilit coral
what?
are u already fix this? or still need help?
try to do ctx.message?
I mean is the cooldown individual for command or is it global
global
!d discord.app_commands.checks.dynamic_cooldown
@discord.app_commands.checks.dynamic_cooldown(factory, *, key=...)```
A decorator that adds a dynamic cooldown to a command.
A cooldown allows a command to only be used a specific amount of times in a specific time frame. These cooldowns are based off of the `key` function provided. If a `key` is not provided then it defaults to a user-level cooldown. The `key` function must take a single parameter, the [`discord.Interaction`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction "discord.Interaction") and return a value that is used as a key to the internal cooldown mapping.
If a `factory` function is given, it must be a function that accepts a single parameter of type [`discord.Interaction`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction "discord.Interaction") and must return a [`Cooldown`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.Cooldown "discord.app_commands.Cooldown") or `None`. If `None` is returned then that cooldown is effectively bypassed.
Both `key` and `factory` can optionally be coroutines.
@terse coyote dm me
If...
My local machine time is 31st Jan (today), and I import datetime, what time will be for datetime?
Your local machine time
Is it possible to send a welcome picture made by the bot in a embed?
Is there a way to permission gate on a cog by cog basis in slash commands? It was possible with regular commands but isn't working with the same code/implementation with slash commands
yeah
dpy im assuming?
embed.set_image()
channel = self.bot.get_guild(payload.guild_id).get_channel(payload.channel_id)
message = channel.fetch_message(payload.message_id)
if str(payload.emoji) == "\U00002705":
for user in message.mentions:```Can someone help?
^^^^^^^^^^^^^^^^
AttributeError: 'coroutine' object has no attribute 'mentions'
C:\Users\llVll\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py:348: RuntimeWarning: coroutine 'Messageable.fetch_message' was never awaited
await self.on_error(event_name, *args, **kwargs)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback```
'Messageable.fetch_message' was never awaited
I asked if its possible
and he told you how, implying that it is possible
bot = commands.Bot(intents=discord.Intents.all(), command_prefix=f"{prefix}") Using pycord
Using intents in discord.py
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.
.topic
Suggest more topics here!
Better support for modals
ok so im trying to make a command where it would match up all nfl teams like the image below, heres the code i have so far ```@bot.slash_command(description="Generate a Schedule")
@application_checks.has_permissions(administrator=True)
async def schedule(interaction):
teams = ["Arizona Cardinals", "Atlanta Falcons", "Baltimore Ravens", "Buffalo Bills", "Carolina Panthers", "Chicago Bears", "Cincinnati Bengals", "Cleveland Browns", "Dallas Cowboys", "Denver Broncos", "Detroit Lions", "Green Bay Packers", "Houston Texans", "Indianapolis Colts", "Jacksonville Jaguars", "Kansas City Chiefs", "Las Vegas Raiders", "Los Angeles Chargers", "Los Angeles Rams", "Miami Dolphins", "Minnesota Vikings", "New England Patriots", "New Orleans Saints", "New York Giants", "New York Jets", "Philadelphia Eagles", "Pittsburgh Steelers", "San Francisco 49ers", "Seattle Seahawks", "Tampa Bay Buccaneers", "Tennessee Titans", "Washington Commanders"]
import random
teams = ["Arizona Cardinals", "Atlanta Falcons", "Baltimore Ravens", "Buffalo Bills", "Carolina Panthers", "Chicago Bears", "Cincinnati Bengals", "Cleveland Browns", "Dallas Cowboys", "Denver Broncos", "Detroit Lions", "Green Bay Packers", "Houston Texans", "Indianapolis Colts", "Jacksonville Jaguars", "Kansas City Chiefs", "Las Vegas Raiders", "Los Angeles Chargers", "Los Angeles Rams", "Miami Dolphins", "Minnesota Vikings", "New England Patriots", "New Orleans Saints", "New York Giants", "New York Jets", "Philadelphia Eagles", "Pittsburgh Steelers", "San Francisco 49ers", "Seattle Seahawks", "Tampa Bay Buccaneers", "Tennessee Titans", "Washington Commanders"]
home, away, test, three, = random.sample(teams, k=2)
await interaction.response.send_message(f'{home} vs {away}\n{test} vs {three}')
I want it so it matches them up and doesnt re use a team twice. Any help?
Make new list that is empty then append random result
Check if the team is in list if not add it to message then send message
what do i append exactly
just random.choice and .pop that choice from the list until list are empty.
uh like this or what
choice = teamz.append(random.choice)
teamz.pop(choice)
ok ill try it
don't append to new list
no reason u already have 2 list
pop will remove them from list
would this be right
this is the error
u already have the var for the choices
home away
so pop those two
W nextcord user
A man of taste
ok so just add home.pop
teams = []
home, away = random.sample(teams, k=2
teams.remove(home)
teams.remove(away)
Your using random.choice and not random.choice(itterable here )
want me to keep the choice thing?
wait
its remove
not pop
ok
do i keep the choice =?
u dont need that
k
unless ur using for something else
u have a blank list
ik
i realized
u override teams
so this good
yes
ok how i can i get to to say all of the teams
and not just 2
for loop and sample 2 until list is empty
ok
i suggest using embed and adding fields
I dont get whats wrong... am i blind?
Its raising this: 'discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction'
async def checkportscommand(interaction: discord.Interaction):
await interaction.response.send_message(f'checking all Ports...')```
?
yeah
thats why i suggesting using embed
its not changing it bruh
and adding fields
its the same team 2 teams every single time thats not the issue
cause ur not doing it right lol i suggest you learn python basics i gave u how to you just don't know how to properly
i legit know python basics
you don't or else you would know how to iterate properly lol
i do
..
not working
A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and practice/competitive programming/company interview Questions.
thats what its doing
i got it for like this but how can i print like the other
any help
is this thing inside an on_message event callback?
no
slash command
what should i do
help
no offense but people aren't going to feed you code
im not trying to get fed code kid im legit asking for help
what am i doing wrong in the code
What is teams?
teams = ["Arizona Cardinals", "Atlanta Falcons", "Baltimore Ravens", "Buffalo Bills", "Carolina Panthers", "Chicago Bears", "Cincinnati Bengals", "Cleveland Browns", "Dallas Cowboys", "Denver Broncos", "Detroit Lions", "Green Bay Packers", "Houston Texans", "Indianapolis Colts", "Jacksonville Jaguars", "Kansas City Chiefs", "Las Vegas Raiders", "Los Angeles Chargers", "Los Angeles Rams", "Miami Dolphins", "Minnesota Vikings", "New England Patriots", "New Orleans Saints", "New York Giants", "New York Jets", "Philadelphia Eagles", "Pittsburgh Steelers", "San Francisco 49ers", "Seattle Seahawks", "Tampa Bay Buccaneers", "Tennessee Titans", "Washington Commanders"]```
So why are you unpacking into home, away in the for loop
Do you want to split the string and get the first word into home and second word into away
sure if thats a way
!d str.split
str.split(sep=None, maxsplit=- 1)```
Return a list of the words in the string, using *sep* as the delimiter string. If *maxsplit* is given, at most *maxsplit* splits are done (thus, the list will have at most `maxsplit+1` elements). If *maxsplit* is not specified or `-1`, then there is no limit on the number of splits (all possible splits are made).
If *sep* is given, consecutive delimiters are not grouped together and are deemed to delimit empty strings (for example, `'1,,2'.split(',')` returns `['1', '', '2']`). The *sep* argument may consist of multiple characters (for example, `'1<>2<>3'.split('<>')` returns `['1', '2', '3']`). Splitting an empty string with a specified separator returns `['']`.
For example:
is there any other ways
because this
That's picking two elements from the list
Which returns a list which can be unpacked
You're unpacking strings in the for loop
remove this entire loop and it works
yall read up
i told him how to do it he just wants the code fed
i dont want the code fed
im clearly asking for help
and i told you you should learn python basics
just leave tbh your no help ur just gonna say harmfull things
what do you expect/want it to send?
you said you know how to iterate properly then proceeded to send this
does that mean i want the code fed?
i told you exactly how you can achieve what you want. you just don't know how to do it because you don't understand python basics
I do
...
^^
read up
all 32 teams matched up agianst each other
in a random order?
yes
then dont use .sample, I recommend .shuffle and then iterating through two of them at the same time
.
he shouldnt be using home and away
yes he should lmao
he has it working fine he just doesnt know how to iterate the list and match all teams
i do im clearly dopig it but just not like 2 time
like its printing the same team
because ur not iterating properly
this is error
there are multiple ways to do this
what are the ways
@slate swan I recommend just using .shuffle with list.join
why would he shuffle lmao
because he wants them in a random order
??
yes random order
do not use shuffle it is of no use to you as you are PICKING items at random out of the list and putting them against each other. all shuffle does is randomize the order of the list
stop misinforming
tahts what hes tryna do
no it is not
random.shuffle(teams)
await interaction.response.send_message('\n'.join(f'{teams[i]} vs {teams[i+1]}' for i in ...```
@slate swan you finish it
ok
or interaction.send
idk what library that is
and you might wanna assert the length of teams is even
thats against tos my guy
no one here is going to help with self botting
The question regarding "self bots" has come up here and there, and we'd like to make our stance clear:
Discord's API provides a separate type of user account dedicated to automation, called a bot a...
am i going in the right direction
not really..
i really suggest you learning basics man. you're just going to keep hitting walls
you gotta understand the logic of what were tryna do here
^
i legit know the basics
stop saying that its so annoying
youre getting the item of teams at index i and index i+1, so that means you need to get an index at 0, 2, 4, 6 until the length of teams
ur trying to iterate 2 variables
and I should indeed consider learning a bit more about iteration before trying a discord bot
can i just do this length = len(list)
Have you used range() before
no none my commands have required it
you gotta think about what youre writing here, home and away will be strings, so youre basically writing this: py for i in 'Arizona Cardinals', 'Atlanta Falcons': ...
now thats obviously not correct
o
Surely you've used it while learning python...
for i in range(0, len(roles)):
if roles[i].name in teams:
team = roles[i]``` like this
ur literally just copying stuff at this point lol
what
i give up
what ru talking abt
jaymart leave your not help at all no one cares π
you just searched range in this discord and copied their code dude
nope thats in my code π
your copying code bro
stop lying man
no im not LOOL
thats been in my code for so long
π
π
nice try though π
Doubt it.
can someone tell me how I can make the bot ignore it's own reaction
on a cog.listener payload
Use a if statement to check if the reaction user was the bot id
What the hell
Whoever wrote this forgor get_channel() and get_role() exist
And uses ineffective searching for named roles
Anyway shouldn't be searching roles by name in most of cases
This isn't as useless as "{}".format(string_instance) but still why do list comp here when you can just use utils.find() (and yeah doesn't have break when team is assigned which is weird)
team = nextcord.utils.find(lambda r: r.name in teams, interaction.user.roles)```
Actually even without using this function you don't need list comp there
team: str | None = None
for role in interaction.user.roles:
if role.name in teams:
team = role.name
break
assert team is not None```
disnake
Imagine
class AdminCommands(Cog, slash_command_attrs={"default_member_permissions": disnake.Permissions(administrator=True)}):
@ebon island
so now all commands within that cog require the administrator permission by default
ooh, interesting, so I'm a little confused about how to wrap that around the cog class though, can you should a little more detail in the snippet for context?
Thank you btw!
You set the meta class option in the class definition
ohhhh I think I understand, let me try
yea it's fairly simple and not much to it
Suuuuuuper easy and awesome! Works exactly how I wanted!!!!!! β€οΈ Thank you!!!
no problem!
I just thought Iβd put this out here for anyone struggling
import discord
from discord.ext import commands
# Initialize bot
bot = commands.Bot(command_prefix="!")
# Assign a channel for mod mail
mod_mail_channel_id = 123456789 # Replace with an actual channel ID
# Command for users to send to mod mail
@bot.command()
async def modmail(ctx, *, message: str):
# Sends the message to the designated mod mail channel
channel = bot.get_channel(mod_mail_channel_id)
embed = discord.Embed(title="New Mod Mail Received", description=message, color=0x00ff00)
embed.set_author(name=ctx.author.name, icon_url=ctx.author.avatar_url)
embed.set_footer(text=f"Sent by {ctx.author} from {ctx.guild}")
await channel.send(embed=embed)
await ctx.send("Your message has been sent to the moderation team.")
bot.run("YOUR_BOT_TOKEN")
Itβs a fairly simple mod mail bot code that I created a little while back
sure but how is anyone supposed to respond?
Haha so I might be asking for Christmas gifts twice in one day but is there a cogwide cooldown handler?
inb4
TypeError: BotBase.__init__() missing 1 required keyword-only argument: 'intents'
you can make one with a cog check
u can then use this
inside of that
class Vanity(AutoShardedInteractionBot):
def __init__(self):
self.pCooldown = commands.CooldownMapping.from_cooldown(
1, 120, commands.BucketType.user)
bucket = self.bot.pCooldown.get_bucket(inter.author)
if retry_after := bucket.update_rate_limit():
return
disnake is cursed
async def cog_slash_command_check(self, inter: AppCmdInter):
this is all you need btw for the cog slash check
in what way? if anything dpy is cursed cause disnake is a fork of it lmao
Naming stuff really. What's AutoShardedInteractionBot and why have the "Interaction" in there 
nah that's just cause the way i imported
and because you have interaction bot and normal bot.
Yikes
?
how to do global cooldown for all app_commands but for one user?
custom cooldown
Just seems weird to have 2 classes for bot. The way most forks rework the implementation of dpy always surprises me
I don't understand how to implement it
i mean it makes sense tho after implementation of slash commands.
Β―_(γ)_/Β―
how can i see the user who invited the bots guilds the user is with
oauth
how
u get the data when they authorize when oauth
where can i see the data]
where data go
!d discord.AuditLogAction.bot_add
only through guild.audit_logs
help
#purge command
@nextcord.slash_command(description="Purges a number of messages from a channel. Max messages 100.")
@application_checks.has_permissions(manage_channels=True)
async def purge(self,ctx,*,number:int):
deleted=await ctx.message.channel.purge(limit=number)
await ctx.send(f'Messages purged by {ctx.message.author.mention}: `{len(deleted)}` (max is 100)')
can someone help me with this error please? i am trying to make a slash purge command. My intents are intents=nextcord.Intents.all())
0|bot | Ignoring exception in command <nextcord.application_command.SlashApplicationCommand object at 0x7f9853f90ac0>:
0|bot | Traceback (most recent call last):
0|bot | File "/usr/local/lib/python3.8/dist-packages/nextcord/application_command.py", line 906, in invoke_callback_with_hooks
0|bot | await self(interaction, *args, **kwargs)
0|bot | File "/home/Runa/bot/cogs/moderation.py", line 20, in purge
0|bot | deleted=await ctx.message.channel.purge(limit=number)
0|bot | AttributeError: 'NoneType' object has no attribute 'channel'
0|bot | The above exception was the direct cause of the following exception:
0|bot | nextcord.errors.ApplicationInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'channel'
how would i go about using interaction? im new to slash commands but i am trying to convert all my commands to slash
self, interaction
also u typehinting will help alot
no its just a naming. its better to keep interactions and ctx seperated
it always uses interaction, you're just naming it wrong
pip install discord.py
make sure you don't have multiple environments
ahh i see. do you know what i should use instead of {ctx.author.mention}? it says AttributeError: 'Interaction' object has no attribute 'author'
.user
got it! thank you both so much
What is the best library currently available/supported for use with Disnake for playing mp3s? Really want one that on demand returns the track position and has seek functionality. I don't want or need anything like YT etc, all of the mp3s will be sourced from a local library. Quite curious what my options are in that regard π
i used wavelink when i did a music bot
@ebon island decent documentation too
https://github.com/PythonistaGuild/Wavelink
A powerful Lavalink library for Discord.py. Contribute to PythonistaGuild/Wavelink development by creating an account on GitHub.
I'll look into it! Thanks, I also saw discord-ext-music but last commit was Oc 19 22 and only 5 stars so not sure if it's at all a viable option
You just install ffmpeg and disnake[voice] that's it
That works?
No need for wavelink at all
Yes why wouldn't it
Oh wow, where can I read docs about doing that?
hahaha relatable π
okay, so if I have imported/installed disnake base package, do I need to specify [voice] as you indicated or will it already be contained therein?
you need to specify.
You need to specify it explicitly
It will install PyNaCl for voice support
Just additional dependencies
could you show me a short code snippet including imports and loading an mp3 from a filepath, then calling the track position method and calling seek?
I'll give it a try ASAP, really appreciate the info btw!
atm I've got people testing a feature in my dev build of the bot so I can't immediately test
I need to recall how to do that give me a minute
ffmpeg is very basic and not as flexible as wavelink which is why I suggested it.
haha sure, thank you!
!d discord.VoiceClient.play
play(source, *, after=None)```
Plays an [`AudioSource`](https://discordpy.readthedocs.io/en/latest/api.html#discord.AudioSource "discord.AudioSource").
The finalizer, `after` is called after the source has been exhausted or an error occurred.
If an error happens while the audio player is running, the exception is caught and the audio player is then stopped. If no after callback is passed, any caught exception will be logged using the library logger.
Changed in version 2.0: Instead of writing to `sys.stderr`, the libraryβs logger is used.
with wavelink you already have built in tracks, queues and some other stuff.
discord.py's voice protocol seems a bit buggy tbh
like 80% of the github issues currently are about the voice protocol
not sure if there's a strong correlation there but it's something
That's disnake tho
so I am already using VoiceClient.play() in my existing code - how do I seek or get the current track position?
you have to code that yourself
I am currently searching docs wait
I thought wavelink was primarily aimed at YT and similar?
no
am I mistaken?
also those voice bugs are in disnake too. it has to do with voiceclient.is_playing() returning True even if audio has stopped.
some weird stuff
well i guess you could say so as it has methods for searching youtube music
docs are pretty nice tho
I'm going to look into it tomorrow for sure, appreciate the suggestion π
Pretty sure I've seen wavelink/lavalink as ToS breaking services
I think because of the YT usage
I know Groovy got shut down cease and desist style for that
hence why my bot is using only community sourced instrumentals
nah it's not against tos
I want no part in that riff raff with Alphabet suing us into oblivion
what's against tos is playing YT music
yall know whats funny. mee6 still has those capabilities lmao
haha yeah
I don't know how some of them, and relatively large bots are still doing that
the vast majority have removed YT functionality
I know this very well as my niche community music centric
TFW when mee6 breaks discord TOS
Anyways if you want to do that with bare ffmpeg
- Install ffmpeg executable (on linux that's just
sudo apt install ffmpegon windows download it from https://ffmpeg.org/ and add to path) - In code just do this
voice.play(disnake.FFmpegPCMAudio("path/to/music")```
@ebon island
yep I have that in my code already actually exen π
the issue is I don't see any way I can natively seek/get position atm
that'd be a great feature to see for sure
Mee6 is the worst moderation bot why tf is it still popular
longevity
Can't even detect amogus if you say amoguss
Probably have if any(word in content.split() for word in blacklist) π
Do you have a Queue implemented ?
Wonder if mee6 devs even know how to do anything other than that
Maybe they could actually tokenize but if their lazy difflib would be good enough tbh
I have my own means of creating a queue
Issue with difflib is it would probably detect all words that end with *uck like duck as blacklisted
it's a 24/7 instrumental music bot for hip hop/rap cyphers
I have words filter that is nicer than mee6's and most of bots' but due to wildcard checking it sometimes detects blacklisted words in not blacklisted ones which is an issue
I haven't actually thought of using difflib
Difflib is pretty comparatively expensive so
I forgot the time complexity but it should be higher than O(n)
But Iβm sure if you can do something like an LALR parser then difflib it would be powerful
was that difflib intended to be a response to my message? lol
I am quite certain it wasn't haha
but I just saw you replied to me with it so I was confused π
Because you compare for each string inside of a sentence, then you compare each position of the tokens
just use openai moderation endpoint
Yeah you're right
An API for accessing new AI models developed by OpenAI
Just use discord automod then π
Aren't openai's APIs paid
nah openai endpoint way better than discord auto mod
^
they have paid version yeah
Open one probably has ratelimits
but there is free usage as well
Should be gestalt pattern matching
they all have ratelimits
So if the bot reaches limit it breaks, who needs that
Yea time complexity of the algorithm is O(n^3) or O(n^2)
Real bad
ehhh if ur reaching limit thats you're own issue
I would hope moderation bots could be used in large guilds otherwise that would kinda break the point
There's no that issue as I am not gonna use it
Yes
again you have to be able to scale your bot lol so that is your own issue if its breaking
It breaks not because of bot but because of limit
???
Developers can use whatever solution
Yea ^^^
it's scalability tho lmao that is a you issue?
Not sure howβd youβd scale a third party API
But your idea relies on OpenAI which as a limit
We are talking that using third party API that has limits is unsuitable for bot that does not put any limits on users
The βscalabilityβ you are talking about would require to upgrade your API key
ding ding ding. that is a you issue
discord api has limits what are u talking ab
Lmao, your logic doesnβt follow
headed to bed, appreciate the tips, I'm going to dig into wavelink tomorrow to give it a try and see how it serves my purpose π
my logic is scaling your bot has nothing to do with limits on a API
Per-user limits
and global????
If 100 users send the message at the same time discord will process that (unless it lags)
Iβm not sure how scaling your bot that relies on an outside API to be optimal
what do you do when you need to scale your bot? you adapt.
Mmmm, yes letβs just pay to get a premium API
so you don't pay to host ur bot?
Should be no issue since the backend is on elixir
Iβm not sure whyd I need more memory, CPU etc for a bot that just posts to an API then decides whether or not to delete the message
And how is top.gg scaling?
because u would be handling more load? lmfao wtf?
Buy a host with GPU and get your own local model (that's gonna be 1k$+ per month probably but who cares)
who the fuck lmao
More load from what? The issue is not the bot taking In messagesβ¦ itβs how many messages can be sent to OpenAI without breaching the free limit
The only thing hardware wise you would need more of is bandwidth
How do you even promote the bots
so ur saying no matter the growth of the bot it will never have an issue receiving messages lmfoaoaoaoaoao?
most ppl just post on top.gg and have ppl vote
Ok ig ima just embed vote webhook into bot
it's really just passive promotion
And add a tip
Yes, because discord has clusters (sharding)
Sure upgrading memory would help with cache as well
and how u gonna shard with the same host u paid for when u started the bot lmao you are making no sense
Lmfoaoaoaoaoao makes this look unprofessional
??
π€
This man is speaking in Minecraft enchanting table
I once set my font in code editor to minecraft enchantment
have you ever dealt with scaling a bot ?
I like using cursive fonts
That was uh magic
Yes, quite a few actually
just curious, and how did you handle it?
sure how u gonna add a cache system on a 2gb ram host tho?
that's right you need to UPGRADE
which is the point i was making the entire time
Again, if you really want to nitpick you can invalidate that point by restricting discord.pyβs automatic message caching
Since you donβt need data to persist long enough, just enough for the API to determine whether or not to moderate
Do you think this activity is alright
wtf
the miniscule server increase makes the graph look dumb. but its not bad most ppl can't even do that in a month
Actually, theoretically you can get rid of the whole message cache since Iβm assuming you donβt need to grab, you only need it on-demand in the MESSAGE_CREATE event dispatched by the gateway
Since your bot solely relies on a third party API
nobody said it solely relies on a tpAPI tho lol it was a suggestion that turned into " why use this if im going to get limited"
and i said thats a you issue as scaling your bot is your problem. if your bot doesn't scale ur fine otherwise you need to adapt
π
pretty nice 7 server net increase
Are there any popular cogs like jishaku that I can download and add to my bot easily?
What can be a potential cause to unknown interaction happening to await defer, despite it being in the first line
Is the only reason that the server is slow?
Can u show the code where this is happening?
Sure, sorry
your internet might be slow
or some part of your code is blocking, causing the request to be sent late
can u check where it might be blocking?
!pypi black you really should use
it makes it faster?
It makes code readable
mk
Hey @slate swan! I noticed you posted a seemingly valid Discord API token in your message and have removed your message. This means that your token has been compromised. Please change your token immediately at: https://discord.com/developers/applications
Feel free to re-post it with the token removed. If you believe this was a mistake, please let us know!
!paste
Pasting large amounts of code
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 floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
The error says what's wrong
I thought it had something to do with my code which it did. I had two config.json just one was in another folder and it was targetting that.
i still have no idea on how to import variables like area and highestArea from another file
if i use class init: it cant be async but define bot
if i use function: can be async but cant define bot
why don't you just take the bot instance in the function
and there's also ctx.bot or something iirc
wdym
lemme try bot = ctx.bot
function parameter
or just ctx.bot.database_handler
lemme try both
you didn't await the function
wait π
Like that ?
the code:
import discord
import random
import string
import asyncio
from discord.ext import commands
intents = discord.Intents.all()
bot = commands.Bot(command_prefix='$', intents=intents)
@bot.command()
async def check(ctx):
await ctx.send("Checking...")
available_usernames = []
for i in range(15):
username = ''.join(random.choices(string.ascii_letters, k=10)) + "#0001"
print(f"Checking {username}")
try:
user = await bot.fetch_user(username)
if user is None:
available_usernames.append(username)
print(f"{username} is available!")
await asyncio.sleep(1)
except:
pass
if available_usernames:
embed = discord.Embed(title="Available Usernames", description="\n".join(available_usernames), color=0x00ff00)
await ctx.send(embed=embed)
else:
await ctx.send("No available usernames were found.")
@bot.event
async def on_ready():
print(f'{bot.user.name} has connected to Discord!')
print(f'With the ID : {bot.user.id}')
what im trying to achieve: a successful discord username checker bot, however it just doesn't seem to work. @hollow quarry
what do you mean by a username checker bot
it checks the random strings as you can see it randomly generates a length of 10
#0001 discriminator
so you want it to check if a username and tag is available ?
correct
I think the main issue would be trying to fetch users that aren't in your discord server
oof
I don't believe you can fetch every single user on discord
And it would take a while
hhhhhhhh
idk anymore
@frosty umbra look at this
thats exactly what im tryna do. π¦
so you're telling me i need to either:
- make a community with a lot of users
- convince people to add my bot to their server
I'm sort of confused for the usage of this
What use does looking up all users with a certain tag have
there is a way to get 0001 discriminator's but i am not allowed to discuss that here.
however nitro, yes.
i already know how
I still wouldn't see a need for og usernames on discord
considering you can just have the username with a different tag
na na na
that means i cant have it
if you try to name yourself with a user#tag that has already been taken, your discriminator gets updated....
exactlyyokwekgegkowgs
yes
not if you have nitro, 
it doesnt
if you have nitro you can do that yourself, why bother using these tricks lol
it says the username aint available
thats what im sayin π
my god can i please speak to someone with an iq higher than 50 π
i wouldn't be the one judging other's IQs if i was in a help channel asking for something that isnt possible
im leaving
bots like dyno and whatever bot's ss you sent above use their internal cache to provide that list
i.e. they have tons of users with that discriminator with them already, they're not fetching it
right
which i said earlier btw
atleast that's what dyno does
its not possible to fetch from all users on discord so probaby most other bots do the same
discord.py supports the latest version of python right?
it does
Which database software should I use for hosting my own database on my VPS, currently using MongoDB Atlas?
That's not discord.py complaining, but your IDE
but why is my IDE shouting at switch case
π
it is really personal preferences
Maybe it doesn't support it yet? Or maybe you've selected a python interpreter with a lower version?
how do i check it
vsc supports py 3.11
so all versions below that should also be supported
are you sure you have 3.10+ installed? @loud junco
pip install python?
no.. your python version
yes you can, but we can't help you with that here if you're planning to use youtube for that
or any other application that doesnt allow bots
!ytdl
Per Python Discord's Rule 5, we are unable to assist with questions related to youtube-dl, pytube, or other YouTube video downloaders, as their usage violates YouTube's Terms of Service.
For reference, this usage is covered by the following clauses in YouTube's TOS, as of 2021-03-17:
The following restrictions apply to your use of the Service. You are not allowed to:
1. access, reproduce, download, distribute, transmit, broadcast, display, sell, license, alter, modify or otherwise use any part of the Service or any Content except: (a) as specifically permitted by the Service; (b) with prior written permission from YouTube and, if applicable, the respective rights holders; or (c) as permitted by applicable law;
3. access the Service using any automated means (such as robots, botnets or scrapers) except: (a) in the case of public search engines, in accordance with YouTubeβs robots.txt file; (b) with YouTubeβs prior written permission; or (c) as permitted by applicable law;
9. use the Service to view or listen to Content other than for personal, non-commercial use (for example, you may not publicly screen videos or stream music from the Service)
do you have a proper knowledge of asyncio and OOP?
even spotify doesnt allow bots streaming
soundcloud does, as long as you're not downloading the songs
this is a basic example
yeah
but you can use the same format for most applications
what's the point of making a music bot 
Turn the question around first, why not?
mhm
*all
yes
Like if don't use youtube what's the point
isn't lavalink a ||better?|| alternative?
ewwie java
and uses youtube again to get music
π
it supports most platforms
that may still break the host's TOS
lavalink servers can be hosted anywhere, doesnt really have to be the same host as ur bot
- soundcloud allows streaming, so y not
Soundcloud does?
!args-kwargs
*args and **kwargs
These special parameters allow functions to take arbitrary amounts of positional and keyword arguments. The names args and kwargs are purely convention, and could be named any other valid variable name. The special functionality comes from the single and double asterisks (*). If both are used in a function signature, *args must appear before **kwargs.
Single asterisk
*args will ingest an arbitrary amount of positional arguments, and store it in a tuple. If there are parameters after *args in the parameter list with no default value, they will become required keyword arguments by default.
Double asterisk
**kwargs will ingest an arbitrary amount of keyword arguments, and store it in a dictionary. There can be no additional parameters after **kwargs in the parameter list.
Use cases
β’ Decorators (see !tags decorators)
β’ Inheritance (overriding methods)
β’ Future proofing (in the case of the first two bullet points, if the parameters change, your code won't break)
β’ Flexibility (writing functions that behave like dict() or print())
See !tags positional-keyword for information about positional and keyword arguments
Positional vs. Keyword arguments
Functions can take two different kinds of arguments. A positional argument is just the object itself. A keyword argument is a name assigned to an object.
Example
>>> print('Hello', 'world!', sep=', ')
Hello, world!
The first two strings 'Hello' and world!' are positional arguments.
The sep=', ' is a keyword argument.
Note
A keyword argument can be passed positionally in some cases.
def sum(a, b=1):
return a + b
sum(1, b=5)
sum(1, 5) # same as above
Somtimes this is forced, in the case of the pow() function.
The reverse is also true:
>>> def foo(a, b):
... print(a, b)
...
>>> foo(a=1, b=2)
1 2
>>> foo(b=1, a=2)
2 1
More info
β’ Keyword only arguments
β’ Positional only arguments
β’ !tags param-arg (Parameters vs. Arguments)
they allow in memory streaming yeah
still same error
TypeError: init() missing 1 required keyword-only argument: 'intents'
!intents
Using intents in discord.py
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.
File "/home/asterv2/site.py", line 1, in <module>
import discord
File "/home/asterv2/.local/lib/python3.9/site-packages/discord/__init__.py", line 20, in <module>
import logging
File "/usr/lib/python3.9/logging/__init__.py", line 26, in <module>
import sys, os, time, io, re, traceback, warnings, weakref, collections.abc
File "/usr/lib/python3.9/traceback.py", line 5, in <module>
import linecache
File "/usr/lib/python3.9/linecache.py", line 11, in <module>
import tokenize
File "/usr/lib/python3.9/tokenize.py", line 34, in <module>
from token import *
File "/home/asterv2/token.py", line 8, in <module>
from ctypes import windll, wintypes, byref, cdll, Structure, POINTER, c_char, c_buffer
ImportError: cannot import name 'windll' from 'ctypes' (/usr/lib/python3.9/ctypes/__init__.py)```
guys can u help me with this error?
everytime i run a code from terminal this will pop up
ctypes.windll doesn't exist
yes i also tried to install windll
but that still pops up
!d ctypes.WinDLL
class ctypes.WinDLL(name, mode=DEFAULT_MODE, handle=None, use_errno=False, use_last_error=False, winmode=None)```
Windows only: Instances of this class represent loaded shared libraries, functions in these libraries use the `stdcall` calling convention, and are assumed to return int by default.
Hello, I am hosting my bot GMT timezone but I want it to be Pacific timezone. How can I change it?
@slate swan
!d datetime.datetime.now
classmethod datetime.now(tz=None)```
Return the current local date and time.
If optional argument *tz* is `None` or not specified, this is like [`today()`](https://docs.python.org/3/library/datetime.html#datetime.datetime.today "datetime.datetime.today"), but, if possible, supplies more precision than can be gotten from going through a [`time.time()`](https://docs.python.org/3/library/time.html#time.time "time.time") timestamp (for example, this may be possible on platforms supplying the C `gettimeofday()` function).
If *tz* is not `None`, it must be an instance of a [`tzinfo`](https://docs.python.org/3/library/datetime.html#datetime.tzinfo "datetime.tzinfo") subclass, and the current date and time are converted to *tz*βs time zone.
This function is preferred over [`today()`](https://docs.python.org/3/library/datetime.html#datetime.datetime.today "datetime.datetime.today") and [`utcnow()`](https://docs.python.org/3/library/datetime.html#datetime.datetime.utcnow "datetime.datetime.utcnow").
takes tzinfo in argument
I have a problem with my discord bot, everything is ok, but it doesnt show the button, heres the code:
@bot.command()
@commands.has_permissions(administrator=True)
async def ticket(ctx):
await ctx.message.delete()
embed = discord.Embed(title ='Tickets', description ='Bienvenido al sistema de tickets.', color=discord.Color.green())
embed.set_image(url='https://cdn.discordapp.com/attachments/1065041520572514304/1065341200950894783/Banner_tickets.png%27)
await ctx.send(
embed = embed,
content = [
discord.ui.button(
label="Crear un ticket",
custom_id="Ticket",
style=discord.ButtonStyle.success,
emoji='π§')
]
)
it responds this:
[<function button.<locals>.decorator at 0x00000239091BDA20>]
can someone help me?
u are missing an await somewhere
the problem must be here:
content = [
discord.ui.button(
label="Crear un ticket",
custom_id="Ticket",
style=discord.ButtonStyle.success,
emoji='π§')
]
)
because theres the buttom
but idk where
and why
im pretty sure its .Button
discord.ui.Button as jaymart say
by the way if i put Button, the bot responds this: [<Button style=<ButtonStyle.success: 3> url=None disabled=False label='Crear un ticket' emoji=<PartialEmoji animated=False name='π§' id=None> row=None>]
wait what lib are u using?
is this a slash command?
no
so ctx doesn't have low level components
you can't do that in dpy
@forest oyster you need to send as a view
ok, if I make the view, how i must put it in the content? examples please
ooooo ok
how can i see the user who invited the bots guilds the user is with
thanks, im going top try it
@slate swan Trying out Wavelink - how do I install base Lavalink atm? I tried downloading the .jar but was unable to find it, has that method changed?
Also, experiencing an issue where codeblocks in embedded messages are not displaying correctly on iphone, is this a known issue?
you just pypi it
https://github.com/PythonistaGuild/Wavelink @ebon island
A powerful Lavalink library for Discord.py. Contribute to PythonistaGuild/Wavelink development by creating an account on GitHub.
probably mobile sucks ass lol
how can i make a command so that when someone authorizes with my bot and They allow the bot to join servers for them, and if they leave the server i can run a command that will pull them back in
also that gh link has the lavalink.jar at the bottom
there are thousands of bots that are public and do that. check GH
what should i look up
restore bot
ok
i dont to restore there roles
This thing has more emojis than Rust repos
lmfao
@slate swan So then how do I configure the lavalink server? Getting the following:
Connection Failure: Cannot connect to host 0.0.0.0:2333 ssl:default [The format of the specified network name is invalid]
seems like the format of the network is fine
and should do localhost
did you change the app.yml?
you have any traceback at all?
in my code When I type A number of 0 - 10 my code is starting to send me messages for when gonna 10 messages
but if != 10 and anyone come's after me and typed number it's not sending messages to him and the client doesn't work != 10.
at discord bot how can I do this
I'm not sure I understand
like think a message sender bot
.message <how much>
I am gonna type .message 5
and it's starting to typing messages
but slowly don't think like (". . . . .") it s like (".") (".") ... if the messages not equal to 5 it's sending when it's equal it's stopping.
but think like that when My message count is 2
the anyone come and type .message blabla
Ah, like a loading dot thing?
the client just sending to me
yeah
and the client can't see his messages
I need help at this
here is my code wait
@client.event
async def on_message(message):
if len(message.content.split(" ")) == 2 and message.content.split(" ")[0] == ".message":
await message.delete() #delete user messages
channel = client.get_channel(1061705379064582204)
await channel.send("**{} in {}: {}**".format(str(message.author), message.guild.name, message.content))
print('gΓΆnderim baΕarΔ±lΔ±.') #send log
if len(message.content.split(" ")[1]) == 10:
telno = message.content.split(" ")[1] #telling number
embed=discord.Embed(title="**MesajcΔ± [8138] ** ", description=(f"**{adet} adet mesaj GΓΆnderiliyor --> #sending message**\n{message.author.mention}"), color=0x001eff) #sending messages
message = Sendmessage(id, "")
await message.channel.send(embed=embed)
while mesagge.adet < adet: # adet = 55
for attribute in dir(Sendmessage):
attribute_value = getattr(Sendmessage, attribute)
if callable(attribute_value):
if attribute.startswith('__') == False:
if message.adet == adet:
break
exec("message."+attribute+"()")
sleep(saniye)
it's not all
but some part of it
@sick birch :(
You're probably getting ratelimited
You can only edit a message a few times in 5 seconds
oh
sorry
@client.event
async def on_message(message):
if len(message.content.split(" ")) == 2 and message.content.split(" ")[0] == ".message":
await message.delete() #delete user messages
channel = client.get_channel(1061705379064582204)
await channel.send("**{} in {}: {}**".format(str(message.author), message.guild.name, message.content))
print('gΓΆnderim baΕarΔ±lΔ±.') #send log
if len(message.content.split(" ")[1]) == 10:
telno = message.content.split(" ")[1] #telling number
embed=discord.Embed(title="**MesajcΔ± [8138] ** ", description=(f"**{adet} adet mesaj GΓΆnderiliyor --> #sending message**\n{message.author.mention}"), color=0x001eff) #sending messages
message = Sendmessage(id, "")
await message.channel.send(embed=embed)
while mesagge.adet < adet: # adet = 55
for attribute in dir(Sendmessage):
attribute_value = getattr(Sendmessage, attribute)
if callable(attribute_value):
if attribute.startswith('__') == False:
if message.adet == adet:
break
exec("message."+attribute+"()")
sleep(saniye)
it's my code @sick birch
You can't work around rate limits
There isn't much you can do
I'm saying it's not possible to fix
oh
if a == 1:
if b == 2:
if c == 3:
if d == 4:
print("ohh I love this stuff")
"ohh I love this stuff"
π that sounds wrong
That's sarcasm
match a:
case 1:
match b:
case 2:
match c:
case 3:
match d:
case 4:
print("ohh I love this stuff")
``` lemme refactor it for u
14 secs
match case scopesπ
Ayo what?
ik how to copy paste and use tabs
First edition sounded funnier
sussy
sounded inappropriate*
!e
print("\n".join(" " * i + f"match {l}:\n{' ' * (i + 1)}case {i // 2 + 1}:" for i, l in zip(range(1, 20, 2), __import__("string").ascii_lowercase)))```
That actually worked
@vale wing :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | match a:
002 | case 1:
003 | match b:
004 | case 2:
005 | match c:
006 | case 3:
007 | match d:
008 | case 4:
009 | match e:
010 | case 5:
011 | match f:
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/mibaxepife.txt?noredirect
@slate swan too bad
.bm
Click the button to be sent your very own bookmark to [this message](#discord-bots message).
lmao
bro really forgot \t is a thing
No tabs in python!
.bm
Click the button to be sent your very own bookmark to [this message](#discord-bots message).
print("\n".join(" " * i + f"match {l}:\n{' ' * (i + 1)}case {i // 2 + 1}:" for i, l in zip(range(1, 20, 2), import("string").ascii_lowercase)))
Code
# <--------------Import-------------->
import asyncio
import contextlib
import io
import json
import os
import random
import sqlite3
import string
import sys
import textwrap
from code import interact
from cProfile import label
from datetime import datetime, timedelta
from io import BytesIO
from operator import ne
from tkinter import Button
from traceback import format_exception
from unicodedata import category
from webbrowser import BackgroundBrowser
import numpy as np
import requests
from discord import Intents, ui
from discord.ext import commands
from discord.ui import Button, Select, View
from nturl2path import url2pathname
from PIL import Image, ImageDraw, ImageFont
``` just some imports
and i get this error anyone knows what i did wrong ?
```line 24, in <module>
from discord import Intents, ui``` because when i delete that line it keeps the error on line 24 so idk what there is wrong
print("\n".join(" " * i + f"match {l}:\n{' ' * (i + 1)}case {i // 2 + 1}:" for i, l in zip(range(1, 20, 2), __import__("string").ascii_lowercase)))```
This is more esoteric than my code
do you know why vs code is bullying me ?
always an error on line 24
About error, is the venv configured properly
idk where can i see that ?
Bottom right corner
is it the interpreter
like why on line 24
just came back after a while i didnt touch anything and i randomly get an error
tried resetting the token
pls help i cant do anything now
alright thanku π
Hold on
There are a few issues with this code:
-
There are multiple imports with the same name, such as
from tkinter import Buttonandfrom discord.ui import Button. This can lead to confusion and errors when trying to use the imported module. -
Some of the imports are not used in the code and are unnecessary, such as
from code import interact,from cProfile import label,from operator import ne,from traceback import format_exception,from unicodedata import category,from webbrowser import BackgroundBrowser,from nturl2path import url2pathname,from PIL import Image,ImageDraw,ImageFont. -
Some of the imports are not compatible with the discord library, such as
import numpy as np,import requests,from PIL import Image,ImageDraw,ImageFont. These libraries are not designed to work with discord and will likely cause issues if used with discord.
4.There is no code that uses these imports, this imports are just taking space and are not doing anything.
I would recommend removing any unused imports, and double-checking that any imports that are used are compatible with the discord library.
Additionally, the imports should be grouped in a logical way, for example, all the discord imports should be together and all the standard library imports should be together.
ok i removed all the unused imports, multi imports, etc but i still get the same error maybe something is wrong with that import but when i remove it it just goes to to the import under it
wait i fixed it huh
Good job.
wow well thanku for your help π
No problem.
just had to reinstall discord
Is there a issue with that?
theres the answer
AttributeError: 'Bot' object has no attribute 'add_roles'
you can't add roles with a bot object it's not possible
are you trying to specify a specific bot to add the roles?
why not shard? or use clusters tho spawning multiple bot instances isn't going to help much
and i don't even know how you would specify which bot to perform a said action such as adding a role to a member
it doesn't work like that tho
you have ur event running through the main client
so that is what is specified to add roles
again i suggest you look into sharding/clustering
i believe what you are trying to do is cluster but the way you are doing it im not sure if that's the most plausible way
A simplistic tutorial on clustering Python discord bots utilizing Docker.
guys how do i make a persistent button for reaction role verification?
so when i turn the bot off and on, the button callbacks are still valid
Databases
and what do i store? the message id?
and how do i continue listening to a view callback?
what? no stop misinforming people
dpy?
dpy 2.0
i agree, but
there are better ways i bet
One way to make a persistent button for reaction role verification is to store the callback data in a database that is not associated with the bot's runtime environment. This could include a remote database service like MongoDB or MySQL, or even a simple JSON file that is read and written to by the bot. Additionally, it would be important to implement some form of user identification, such as a unique user ID, to ensure that the callback data is only applied to the correct user. This way, when the bot is turned off and on, the callback data can be loaded from the database and reapplied to the correct user, allowing the button callbacks to remain valid.
using a database is not a way to make a button persistent lmao
Yes it is.
what is chatgpt answer? ππ
nice openai answer bro shut the fuck up
hey still not nice to say that
can we stop arguing, and talk about code
in that case i agree
keeps misinforming ppl and copy pasting others code
chatgpt answers are banned here fyi
then asking why the pasted code doesn't work
I named a way on how you can, and this kid is angry for no reason.
XD
+1
how does a database make a persistent button lmao
read
jaymart, no point in that arguint, can you help me tho
ANYWAYS set the timeout to none and assign a custom_id
and where will the custom id be stored
implement identification for discord
the fucking button itselfs u moron
It wont be saved if the bot restarts π
holy shit
i cant can this kid be banned from this chat
that could only get you in trouble, but i know youre not the one in the wrong, but still not nice
Calm down
Jay can cry more im just giving an answer and hes crying over it.
u need a database for sure
and misinformed answer that does not work
Yep.
but that is still not an answer i was looking for
YOU DONT NEED A DB
I never said you need one, I suggested that as one way.
You do need a database if you want to make the persistent view work regardless of the guild. If you're just making it for a single server, you don't require one because you can just hardcode the custom ID
Exactly, and jay is crying that in misinforming.
what? no u dont lmao
what the fuck
thx
you're welcome man
I will be reporting jay with the modmail now.
no use. they wont remove them from chat from misinforming they would just tell them to stop lol
jay was a lil not nice but, thats ok
yesterday we was helping this kid and he kept asking and we told him and he was spamming chat waiting for someone to feed code. so someone gave him half of some fed code and he still couldnt get it to work. i suggested learning python basics he said he does but couldnt understand how to iterate. then he copied someones code pasted it and asked why it didn't work
now he is misinforming people
If you have the same view across multiple guilds with the SAME custom ID, the view is gonna respond in a non-unique way. If you add a role from one guild, it will be accessible from any other and the verification thingy will become pretty pointless and useluess
what bro
the custom_id only IDENTIFIES the button lmao
the interaction is a per guild basis
not a per bot basis wtf are u saying/
without custom_id the bot can not identify the button
no need for that language, that will only get u in trouble
You still have a custom ID, it's just not hardcoded
Yup
which is why setting a static one allows u to reuse the button even when restarting
Which is why you save the custom ID in a database... hence you need a database
Yep.
i even sent the EXAMPLE FROM DPY ITSELF
lmao where does it show or tell you to use a db?
There are multiple ways to doing this, we are simply suggesting one way. Who said that wasnt a way?
you didn't suggest shit. u asked chatgpt which again is banned from here so stop talking
?
+1
No I didnt, I had that saved from the Nextcord discord for when I asked that question.
i mean, still that answer was bad, so please stop sending openai answers, but still
That isnt an openai answer or chatgpt answer. I legit just said what it was.
cap lol that is so cap
And it wasnt bad, that is a very good way of doing it.
no lol
can you all 3 shut the fuck up and go somewhere else this is a help channel not a argument channel
okay big brain explain how using a db allows a button to be reused after restarting the bot lol
you have a point, but the audacity is just wow
^ Read
that literally does not tell u how at all lmfao
+1 literally
Sigh I guess your blind.
This is literally chatgpt
Well I didnt get it from there, I got it from the official Nextcord server when I asked that same exact question.
...
exactly
Let's say I've got a simple command that creates a persistent view
@bot.tree.command()
async def persistent(interaction: discord.Interaction, verify: discord.Role) -> None:
await interaction.response.send_message(MyPersistentView(interaction.guild, verify.id))
now let's define our view. For the sake of simplicity it's only gonna have 1 button
class MyPersistentView(discord.ui.View):
def __init__(self, guild: discord.Guild, role: int):
self.role: int = role
self.callback.custom_id = f"verify-callback:{guild.id}"
# Save the guild ID and role ID in your database
@discord.ui.button(label="Get a role!")
async def callback(self, interaction: discord.Interaction, button: discord.ui.Button):
await interaction.user.add_roles(discord.Object(id=self.role))
Great! Now we have our view, and our command. Now we also have to add the view so it stays persistent
@bot.event
async def setup_hook():
for row in database:
for guild_id, role_id in row:
bot.add_view(MyPersistentView(discord.Object(id=guild_id), role_id))
Ta-da! Now you've got a persistent view that works across multiple guilds
thank you ^ actually useful
I'm proving syfe's point lol
Exactly.
and also proving jays point,
but i asked my questions, jay gave official doc link, most useful, no need to keep going about this :D
ok but why do you need a database to setup a persistent view
lmao
it's literally 1 view no need for a db
You don't need it if it's only for 1 guild
exactly what syfe said so literally no point in going again over this
You never said if it was for one guild or not.
exactly this is going to a extreme for no reason
true, i never said it was for more than 1 either, so
even if it's not one guild you still do not need this?
^^
your doing what discord already does?
^^ so can we stop about this please lol
π€· There are multiple ways to code exactly the same thing, do as you like and don't start calling people "misinformant" just because you don't like their method
its not about him not liking the method, its clearly an openai answer, which is not ok here, but fine who cares who cares about this
oh really? so telling someone they NEED a db to make a persistent view isn't misinforming? lmfao
I'm just providing a solution that I'm familiar with to a problem, there's no misinformation in that
syfe was misinformative.
technically sure you can say that there are many ways to do things sure but there exists a hammer to hammer nails, and a knife to cut things
nah we got someone in here pasting other peoples code and chatGPT answers to peoples questions
its clearly an openai answer,
Yes, and I agree that using an AI to "solve" issues isn't the most smart thing to do, specially with code
There are multiple types of hammers to hammer the same nail, and multiple knifes to cut the same thing :p
I'm not gonna argue if syfe was misinformative or not, I'm just saying that there's a method to create persistent views in which you can use a database
iβm not reading it all, all i know is #announcements message
^^^
sure, i agree
but ALL i needed was to add
@discord.ui.button(label="Verify", style=discord.ButtonStyle.green, custom_id="persistent_view:green")
# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
and then self.add_view in setup_hook
but thanks to everyone who helped !
I'm glad you could solve your issue
@slate swan there's no excuse to calling people names. If you have an issue with another member, you involve the moderators. Next time I'm just going to mute you.
@slate swan If you used ChatGPT or other AI tools to generate this answer, you need to stop. It was confusing and not very helpful in the context of the question.
Im not, I've already said many times I got this answer from the Official Nextcord server when I asked that exact question.
thanks. he is also pasting other people's code from this discord itself and asking why it doesn't work. ima just block him as he is trolling at this point
Fine with me.
@bot.command()
@commands.is_owner()
async def prepare(ctx: commands.Context):
"""Starts a persistent view."""
# In order for a persistent view to be listened to, it needs to be sent to an actual message.
# Call this method once just to store it somewhere.
# In a more complicated program you might fetch the message_id from a database for use later.
# However this is outside of the scope of this simple example.
await ctx.send("What's your favourite colour?", view=PersistentView())
you can as use a database as well, as listen in the official doc
Hows that chatgpt?
looks like openai to me
definitely openai
?
!e
# message id 1066070844352254012
start = 1674241495
# 1066070287239622797
end = 1674241363
print(start - end) # 120
@iron sorrel :white_check_mark: Your 3.11 eval job has completed with return code 0.
132
this is referring to the message_id tho. im not sure the use case exactly tho
im guessing if the bot doesn't already have access to the message itself?
it would need to fetch it
!e
text = """
There are a few issues with this code:
1. There are multiple imports with the same name, such as from tkinter import Button and from discord.ui import Button. This can lead to confusion and errors when trying to use the imported module.
2. Some of the imports are not used in the code and are unnecessary, such as from code import interact, from cProfile import label, from operator import ne, from traceback import format_exception, from unicodedata import category, from webbrowser import BackgroundBrowser, from nturl2path import url2pathname, from PIL import Image, ImageDraw, ImageFont.
3. Some of the imports are not compatible with the discord library, such as import numpy as np, import requests, from PIL import Image, ImageDraw, ImageFont. These libraries are not designed to work with discord and will likely cause issues if used with discord.
4.There is no code that uses these imports, this imports are just taking space and are not doing anything.
I would recommend removing any unused imports, and double-checking that any imports that are used are compatible with the discord library.
Additionally, the imports should be grouped in a logical way, for example, all the discord imports should be together and all the standard library imports should be together.
"""
print(len(text.split()) / 2.1)
@iron sorrel :white_check_mark: Your 3.11 eval job has completed with return code 0.
97.14285714285714
97 words per minute + formatting, you really are trying to hide the fact that its openai?

Hi!
yo
hi venom
So i have this code and the bot does not assume the command
do you have the message.content intent enabled on discord dev portal?
This?
yes
you need that intent to be enabled, on discord + inside your bot's code in order to receive the message's content
I have already enable on discord, what do I need to put in the code?
I'm new to programming xD
!code show your current code
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
print('Hello world!')
TRUEEE
!code
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
It isn't working

xD
we know 3 things:
you got something
we don't know what you got
what you got doesn't work
I will prtsc 1 sec
and you get an error about intents don't you
I don't get any error, the command "!OlΓ‘" doesn't do anything when I try to run it on the chat
and I don't know why

