#discord-bots
1 messages · Page 373 of 1
oh and uh in the description it should be Total Members
just a minor spelling mistake đż
hey, mind if i show you my code in dms? i need a bit of help but i dont want to send all of it here
alright?
is that a yes? im asking if thats okay
Mb
Anyone hosting their discord bots on render.com? need some help
Heya
I'm using Python and Nextcord to make a discord bot and I'm trying to create a button that adds a specific role (verification role). Does anyone know how to code a button like that? It would be handy if that role couldn't be removed too so that members don't verify and then unverify.
I'm a noob so any help would be appreciated 
hmh, why use nextcord instead of discord.py nowadays?
anyways, i think you want a persistent modal? https://github.com/nextcord/nextcord/blob/master/examples/modals/persistent.py has an example
although discord itself has a thing like this for community servers now, you could use that instead of reinventing it, but eh, whatever
I think they want a persistent button
I've tried copying in the server's rules into onboarding but there were too many. Onboarding has a limit on how many rules you can add 
Most people want to know what rules they agree to when they join a server. I don't like them just agreeing and finding out later what they agreed to.
Yh just a button people can click that gives them a role but the role can't be removed by clicking the button again. I'll look up persistent button 
I've made modals before
I just don't know how to get the bot to add roles with a click of a button
I guess it's like making selfroles
A Python wrapper for the Discord API forked from discord.py - nextcord/nextcord
you can use this example
and have the logic to check if a user has the "verified" role
I appreciate the help <3
Ooo thanks
hey guys does the voicechannel class not have a .play function anymore?
i dont see it in the docs
how do we get bots to play music in the vc then?
i got it to connect and i have the file
i might sound dumb but how do i create an instance of VoiceClient to use the .play() thing
i have only vc rn
guild.voice_client should work
will i not need to specify the vc id or anything?
so just guild.voice_client.play(......) ?
k ill try
its not playing anything neither is it giving an error idk whatds wrong
self.vc.play(discord.FFmpegPCMAudio(song, **self.ffmpeg_options))
self.vc is the voiceclient
song is the url
ffmpeg_options = {'before_options': '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5','options': '-vn -filter:a "volume=0.25"'}
do uk whats wrong?
error
File "/home/runner/xylan/src/music.py", line 76, in play_music
self.vc.play(discord.FFmpegPCMAudio(song, **self.ffmpeg_options), after=lambda e: asyncio.run_coroutine_threadsafe(self.play_next(), self.bot.loop))
File "/home/runner/xylan/.pythonlibs/lib/python3.10/site-packages/discord/voice_client.py", line 614, in play
self.encoder = opus.Encoder()
File "/home/runner/xylan/.pythonlibs/lib/python3.10/site-packages/discord/opus.py", line 323, in __init__
_OpusStruct.get_opus_version()
File "/home/runner/xylan/.pythonlibs/lib/python3.10/site-packages/discord/opus.py", line 316, in get_opus_version
raise OpusNotLoaded()
discord.opus.OpusNotLoaded
Unless you have the copyrights to this music or it's royalty free, may want to double check the tos
Update: It worked! 
all text currently
L discord
Well then im here for an IDEA. How can I get a country, but then need to import a flag but an emoji basically, just skip to 1:23 in the video
Skip to 1:23 in the video, how can I improve the country feature?
they had it before but it got removed
Can you do autocompletes in modals?
no
ii cant see any
@elder vale what about SD?
probably typo of "sad"
standard definition (real)
Well this is how I decided to do country I guess lol
wish I couldve done it in a modal
but modals are limited on "support"
code : py @bot.command(name='helpp', description='asd') @commands.cooldown(1, 15, commands.BucketType.user) async def helpp(ctx): embed = discord.Embed(title=f'Lista de comandos ({len(bot.commands)})', color=0xEBE8EC) for command in bot.commands: embed.add_field(name=f'{bot.command_prefix}{command.name}', value=command.description, inline=False) await ctx.send(embed=embed) error: Command raised an exception: HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body In embeds.0.fields: Must be 25 or fewer in length. how fix?
do you have more than 25 commands?
36 commands
embeds can have a max of 25 fields
đ
any1 know whats wrong?
are you trying to run music from YouTube?
yea
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)
its against toc?
what to do the bots use then
most of them use YouTube, you could use soundcloud too
major music bots have gone down, it's just the small bots
that use youtube
oh kk
its annoying they don't like you downloading videos ig its about ads and stuff you don't get served ads if you have it downloaded
raise OpusNotLoaded()
discord.opus.OpusNotLoaded
what does this error even mean tho?
I mean, if you owned something like YouTube, even you wouldn't want bots to eat your revenue away right
if I owned something "like youtube" it wouldn't be a money grabbing corporation but rather a video sharing platform based around comunity that anyone is welcome to save content they enjoyed on
so. actually you couldn't be more wrong
how're you gonna pay the content creators then
And it's easy to say that, but practically that's not possible
I mean who would miss their chance to scale their application to a billion dollar company
me. because billions are generally built on wage theft and also usually require outside investment. which means there would be outside stakeholders other than employees
also. there are already bots downloading youtubes content. the TOS does little about it
youtube is profitable. therefore. it would be proftiable if that weren't in the TOS
don't know, if it's against the TOS, I would rather support it than illegally use it even though there are no consequences
aight its pointless to argue
sorry. not arguing. you're entitled to your opnion I am just curious about the movite. it sounds strange to me is why I was laughing. you're entitled to your opinion
I'm not trying to ridicule you that might have seemed rude. its just to me kind of yano "what lol" cos i don't get it but thats fine
đ
personally I always advocate for trying to do whats RIGHT. and that be the be all and endall
but we'll leave this there
How long until all music bots are banned?
uh yeah. we were just having a casual convo. uh sorry
they brought rythm back as an activity
and they are surely ruining rythm all together
How do I make my looped task not do an initial run on bot startup?
@tasks.loop(minutes=3)
async def squadlogs_updater(self):
await asyncio.sleep(5)
print("------------------------")
```When I turn my bot on, and do `self.squadlogs_updater.start()` this will run after 5 seconds instead of 3 minutes
No.
oh wait
You misunderstand. When I load the bot, the task runs when the bot loads so I had to put that sleep in so the bot can load properly.
I dont want the task to run right away when the task is started, I want it to wait 3 minutes
You can set a flag in your class's __init__ method that tells the task whether to wait longer.
why dont u just check if atleast 3 mins has passed since the bot has started if not return just store an attribute
like bot.uptime
another way is u use something like asyncio.create_task and add a sleep of mins before calling squadlogs_updater.start
hi everyone
i need to find out how to make a command user installable and guild installable
In the end I decided to just add a boolean to the class called "first_run" and checked if it was true, if so, returned if not run the loop
You could just put whatever in the before_loop btw
eh this works and im happy
solstice isn't
I dont really know how to make my embed look like the first one, how?
Will somebody help me gahdamn
A hands-on guide to Discord.py
Just copy the first example
Change to suit your needs
Remove items you dont need
And done
uhhmmm, guys how do I receive multiple Role objects in a single argument
something like
roles: Role #need to have multiple roles
wasn't there something like Greedy that ws usually used?
yeah there's Greedy too
depends on if you wanna raise an error or not if it can't parse an argument
aight, thanks
nw
can you guys help with discordpy-self?
no
why
it's for my own server and discord.py already supports self bots i dont see the problem
No, it doesn't
discord.py doesn't support self bots anymore
i'm trying to make it so i automatically respond when someone says hi
and it's against ToS
do they not work with discord.py
Please refer to the rules here
anyone here use pycord instead of discord.py?
probably
thinking of using pycord instead of discord.py ngl
why
tbh rn i'm just checking my options for my next bot
!paste
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.
hi
don't ask to ask
okay so i really can't figure out how to do a guild installable & a user installable command at the same time
like if i do user install guild install wont work
idk how to fix it, this sucks 
Hey guys im trying to send a view to a webhook, using view=ButtonSendCode(). Im doing await webhook.send(embed=embed, view=ButtonSendCode()),
however it keeps erroring any help?
ValueError: Webhook views require an associated state with the webhook
Thats the error code ^
when you instantiate the webhook, i.e using webhook.from_url, you need to gives it a state from your bot for views i believe, ```py
webhook = discord.Webhook.from_url('webhook url', client=bot)
Check DMs
hi ^^' how can i make the bot to have localized languages?
!d discord.app_commands.Translator
class discord.app_commands.Translator```
A class that handles translations for commands, parameters, and choices.
Translations are done lazily in order to allow for async enabled translations as well as supporting a wide array of translation systems such as [`gettext`](https://docs.python.org/3/library/gettext.html#module-gettext) and [Project Fluent](https://projectfluent.org).
In order for a translator to be used, it must be set using the [`CommandTree.set_translator()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandTree.set_translator) method. The translation flow for a string is as follows:
thanks
if reaction.emoji == '1\uFE0F\u20E3':
with open(FILE,"w") as fp:
json.dump(DEFAULT_DATA,fp)
print(icon)
print(icon is None)
if icon is None:
print("running")
await set_icon(channel,ctx)
await add_teams(ctx,channel)
await set_cap(ctx,channel)
await preseason(ctx)
hey in this code, all the functions past set icon are not waiting for set icon to finish, anyone know the reason why?
why is ctx first for every other function but 2nd for set_icon?
(http) APIs are language agnostic
you can use them from any language
thanks
hi
@bot.command()
async def send(ctx, user: int = None, *, message):
if user is None:
await ctx.send("Tu dois spécifier l'ID de l'utilisateur.")
return
try:
target_user = await bot.fetch_user(user)
except discord.NotFound:
await ctx.send("Utilisateur non trouvé.")
return
except discord.HTTPException:
await ctx.send("Erreur lors de la récupération de l'utilisateur.")
return
try:
await target_user.send(message)
await ctx.send(f"Message envoyé à {target_user.name}.")
except discord.Forbidden:
await ctx.send(f"Je n'ai pas la permission d'envoyer des messages Ă {target_user.name}.")
@bot.event
async def on_message(message):
print(message.author.id)
print(bot.user.id)
if message.author.id == bot.user.id:
return
if isinstance(message.channel, discord.DMChannel):
embed = discord.Embed(
title="Nouveau message reçu",
description=f"Contenu du message : {message.content}",
color=0x00ff00)
channel = bot.get_channel(1251915975746650244)
if channel:
await channel.send(embed=embed)
else:
print(f"Le salon avec l'ID {1251915975746650244} n'a pas été trouvé.")
else:
print(message.channel.name)
await bot.process_commands(message)
@slate swan can u help me pls
I think i missed the part when you actually Ask your question
@slate swan
You never said what's the issue nor asked any questions
the bot send twice the message "message recu"
but i don't want it to send that message
Bot likely running twice
is the bot running on two different instances
i need both the channel id and object
no
are you sure
it is best to store channel object in dict key or the channel id
smth[channel.id] = {"channel": discord.TextChannel}```
OR
```py
smth[channel] = {"author": commands.Author}```
no particular reason, i have it set up right though
sorry to barge in on a tangent but you guys seen the changes to premium bots? I don't make them. I don't use them. still sad and disappointing
how do i make it like:
i type the command !numbers
the bot reacts with number emojis (1ïžâŁ, 2ïžâŁ, 3ïžâŁ, ...) from 1 to 9
i react on one of them
it returns the number (1, 2, 3, ...) i reacted on
why not use buttons
I think its illegal
???
I need to make a bot for slack
Hi I am new here
I want to send the responses that have errors in them in the django server to the slack server so the team can work on them
just make a discord server with your team
why do you wanna overcomplicate things
Or just make a UI in your django server to view and work on the errors
i'll shoot my shot here đ€
So i have started to code my own bot, i have absolutely no knowledge on how to, but a basic understanding
im using python and visual studio code, i have wrote the first part of the bot, ran the file and got no syntax erros, but when i try to run the command from the terminal in VSC it doesnt work and this is the error i recieve
C:\Users\gavin> python WNW1.py
Traceback (most recent call last):
File "C:\Users\gavin\WNW1.py", line 4, in <module>
client = commands.Bot (command_prefix= '/')
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: BotBase.init() missing 1 required keyword-only argument: 'intents'
!intents
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. Various features of discord.py rely on having particular intents enabled, further detailed in its documentation. Since discord.py v2.0.0, it has become mandatory for developers to explicitly define the values of these intents in their code.
There are standard and privileged intents. To use privileged intents like Presences, Server Members, and Message Content, you have to first enable them in the Discord Developer Portal. In there, go to the Bot page of your application, scroll down to the Privileged Gateway Intents section, and enable the privileged intents that you need. Standard intents can be used without any changes in the developer portal.
Afterwards in your code, you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:
from discord import Intents
from discord.ext import commands
# Enable all standard intents and message content
# (prefix commands generally require message content)
intents = Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see discord.py's related guide, and for general information about them, see the Discord developer documentation on intents.
boss says i do
hmm I see
you can use this guide to learn how to make bots -> https://fallendeity.github.io/discord.py-masterclass/
A hands-on guide to Discord.py
Disclaimer that this guide is not endorsed or reviewed by the library maintainers. The API docs and examples in the relevant library you're using will be definitive
where is this missing from?
?
sorry, i thought you had replied to my post
I did, read the thing the bot sent, you're missing the intents=... from your code.
im so lost, i started by watching a step by step on YouTube, the code i have is exactly the same as the video, but mine won't run in the terminal
That video is outdated then
i did this now... i think, do you mind if i send you a Screenshot of it? this is my first attempt at a bot with very basic knowledge
sure
i sent a DM âïž
Hey! Am I missing something or is there just no documentation for slash commands in discord.py?
I found a 3 year old post on stackoverflow and thats it
the official guide is still WIP so you'll have to make do with their API reference, examples, and some third-party guides (or ask about it here of course)
https://discordpy.readthedocs.io/en/stable/interactions/api.html#decorators
https://github.com/Rapptz/discord.py/blob/v2.3.2/examples/app_commands/basic.py
https://about.abstractumbra.dev/discord.py/2023/01/30/app-command-basics.html
https://fallendeity.github.io/discord.py-masterclass/slash-commands/
The last one real
tysm
I don't see in documentation the last thing I need... any idea how to increase time before a slash command will fail and respond with command timeout?
interaction.response.defer() is what you'd use for that
!d discord.InteractionResponse.defer
await defer(*, ephemeral=False, thinking=False)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Defers the interaction response.
This is typically used when the interaction is acknowledged and a secondary action will be done later.
This is only supported with the following interaction types...
note that deferring is itself a response so your subsequent message will need to be sent as a followup, i.e. interaction.followup.send(...)
Can someone help me In https://discord.com/channels/267624335836053506/1252328347552448583 ?
im tryna pip install yfinance but it doesnt work, any clues? maybe its an issue with the environment
it works in other files perfectly, its just this folder where it doesnt seem to detect the pip
did you enable the Virtual environment?
elaborate
you need to execute this command to enable the venv
./.venv/scripts/activate
tho you probably need to update Windows powershell polices before that
np
to exit it you just need to type deactivate
ah ok
is anyone able to help with errors on my bot? wrote on python using visual studio code
i connected it to nitrado and ran it, it went online but wasn't sending logs as i didnt import requests
wince i imported requests and set my command to get the logs, it now won't recognise my nitrado api đ€
Code and errors would be a good start.
If you're using an asyncio framework like discord.py (or any of its forks), you really should not be using requests at all
I was trying to implement this today and looks like you can either use bot.commands hybrid command or the tree command way. But from what I read you canât use the tree commands in extensions or cogs so wasnât sure how to abstract the tree commands into their own file
I was initially using Disnake last time I made a bot so feel like I might go back to it as felt better the way it handled slash commands
that article was mistaken, you can use tree commands in cogs with @app_commands.command() just like how the decorator for text commands change from @bot.command() to @commands.command()
markdown in title doesnât work, why?

who wants to make a discord bot using openai?
XD
I just use gpt4free
a quick peruse of the docs makes me think this is not available but you could do something like py @bot.command(name="trigger") async def get_member_messages(ctx, member: discord.Member): await ctx.defer(thinking=True) total = 0 for channel in ctx.guild.channels: if isinstance(channel, discord.TextChannel): history = channel.history(limit=None) async for message in history: if message.author.id == member.id: total += 1 await ctx.send(f"{member.mention} has {total} messages sent")
it does take a long time
and a lot of requests
You are not allowed to use that command here. Please use the #bot-commands channel instead.
Ok I looked at the source ode
It basically adds to a counter every time you send a message
Thereâs not a way to get it as a value unfortunately
I haven't had time to play around with the globally installable apps yet - but can they DM the user that it's installed for? I've got some project ideas with these but they require being able to DM the user for which it's installed under. Tried looking at the docs but it seems to focus mostly on the ablity to be invoked from anywhere (and their interaction responses)
i had a skill issue
@commands.Cog.listener('on_message')
async def ai_listen(self, message : Message):
ctx = await self.bot.get_context(message)
user_id = f"{ctx.guild.id}-{ctx.author.id}"
if message.author.id == self.bot.user.id or not self.bot.user.mentioned_in(message):
return
if user_id not in context_window:
context_window[user_id] = []
context_window[user_id].append(f"{message.author.name}: {message.content}")
if len(context_window[user_id]) > config["MAX_CONTEXT_WINDOW"]:
context_window.pop(0)
await ctx.channel.typing()
attachments: Attachment = message.attachments
remembered_memories = Memories().compare_memories(user_id, ctx.message.content)
if remembered_memories["is_similar"]:
prompt = read_prompt(ctx.message, remembered_memories['similar_phrase'])
else:
prompt = read_prompt(ctx.message)
if attachments and attachments.filename.endswith(".png", ".jpg", ".webp"):
save_name = f"{message.guild.id}-{message.id}"
attachments.save(save_name)
image = Image.open(save_name)
await ctx.reply(BotModel.generate_content(prompt, user_id, image), mention_author=False) # download attachments[0] in `attachments`
else:
await ctx.reply(BotModel.generate_content(prompt, user_id), mention_author=False)
^^ - Relevant code
Traceback (most recent call last):
File "c:\Python312\Lib\site-packages\discord\client.py", line 444, in _run_event
await coro(*args, **kwargs)
File "d:\Python\Gemini-AI-Bot\v0.5a\cogs\ai_beta.py", line 49, in ai_listen
attachments.save(save_name)
^^^^^^^^^^^^^^^^
AttributeError: 'list' object has no attribute 'save'
You may wish to review the updated developer TOS going live on July 8th
does it say something about AI not allowed
Yes
- Do not use message content obtained through the APIs to train machine learning or AI models (including large language models) unless express permission is granted by Discord.
i am not training the model lol
i am also aware of the updated TOS
your analysis would be correct o3ob, i'm using gemini to send a message with context and pictures if there are any
Right, because you know what Gemini is doing under the hood with what you send it stuff, and you're also adhering to the requirements of sending user data to third parties I bet
understood, i will probably have to request permission, thank you for the clarity
or ill just end this project, i literally cant face anymore roadblocks, i've been working on this shit for 12 days straight and every time i make progress i lose it
im just gonna put it on a shelf until i can even feel sane
i'm too tired to find the tone of this message, i was going to write a long paragraph but i dont want to misread it and get on someones bad side lmao
disregard my previous messages, i was not in a state of mental clarity when writing them. i do apologize and thank you for your time
You're fine, it's just important to understand the responsibilities when you're passing user data along to third parties. The line of "training" or not is murky when you don't actually control the model
i wish i could use Gemma 2b and just cut it offline lol, i really do. but my computer is too slow for it to even generate the response in a meaningful amount of time
my entire computer turns into a slideshow the second i run the model and it loads the model checkpoint, and then it takes an additional 20 minutes to produce a response along the lines of
"Iâm not sure what you mean by âwrite me a poem about Machine Learning.â"
however i digress, and must accept this as a skill issue.
Tbh haven't dug into what the guarantees are on how Gemini uses api inputs, but you're effectively sticking your neck out for them. Plus that's on top of the requirements for any sharing of user data with third parties (getting and recording the user's explicit instruction to do so)
yeah, i can't wait to wake up one day and see Gemini starting to use my inputs as potential training data.. i dont think theyre doing that yet
idk what we're discussing, but it doesnt look like code.
So can someone share code so I can be reminded what it looks like
rn while using the @commands.has_any_role() i'm passing thru a list of role names (it works). if i use role IDs will it work the same or do i need to add extra steps (getting the roles from the IDs)?
it works the same way
thanks
is anyone around able to help, currently on day 2 of an issue with my bot
coding on VSC, everything was working as it should until i asked it read logs from nitrado, now i get this
line 26, in <module>
client = commands.Bot (command_prefix="/"),
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: BotBase.init() missing 1 required keyword-only argument: 'intents'
you have a space between Bot and (command_prefix="/")
still returning the same messGE
did you save it before running again?
omg i just noticed you don't have intents specified lmao mb
after your prefix, specify intents with intents=
i mean i have my intents set to
intents = discord.Intents.all(), but you can specify them separately
intents = discord.Intents.all()
bot = commands.Bot(command_prefix=commands.when_mentioned_or('.'), help_command=None, intents=intents)
this is from my code :p
i was just about to ask, do i put in just intents=intents or is there anything else should add
thank you bud âïž
<3
it's now created new errors on different lines đ«
its at this point i feel like scrapping it all and starting again, it worked as it should until i tried to get it to read logs from nitrado, so i could add command in later but its not playing ball now haha
send the error n code
but if it's sumn nitrado related i can't help cs i ain ever touch it befo
client = commands.Bot(command_prefix="/"), intents=intents
this is the line of code
client = commands.Bot(command_prefix="/"), intents=intents
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='?
this is the error...
i have tried == and := but still errors out
what do you think that this part of code does? 
commands for the bot
commands the bot to do what?
the funny thing is
this is erroring on the part of the bot tha actually worked yesterday
@client.event
async def on_ready():
print("the bot is now ready for use")
print ("----------------------------")
@client.command()
async def goat(ctx):
await ctx.send ("CR7 SIUUU VAMOS PORTUGAL")
yeah, for sure it didn't work yesterday if it was exactly what you sent
the intents kwarg should be passed as an argument in the place where you initialize the bot, just like command_prefix
!d discord.ext.commands.Bot
class discord.ext.commands.Bot(command_prefix, *, help_command=<default-help-command>, tree_cls=<class 'discord.app_commands.tree.CommandTree'>, description=None, ...)```
Represents a Discord bot.
This class is a subclass of [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client) and as a result anything that you can do with a [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client) you can do with this bot.
This class also subclasses [`GroupMixin`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.GroupMixin) to provide the functionality to manage commands.
Unlike [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client), this class does not require manually setting a [`CommandTree`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandTree) and is automatically set upon instantiating the class.
async with x Asynchronously initialises the bot and automatically cleans up.
New in version 2.0.
your right, the top line of code wasn't there
then you would probably also get some error because client is not defined
guess who feels like a prized tit now
its working
after removing the line that was giving the error... because there was nothing after the line of code except yesterdays command
đ€·ââïž you probably have a client defined somewhere else if it works
i say works, the bot goes online without any errors, but it progress
maybe, but everyone starts somewhere đââïž
yh but i shouldntve spoonfed lmao it's against the rules
i mean idk if it's an actual written rule but it's a bad habit
it's better to learn rather than copy and paste code without actually understanding your mistakes
@slate swan where does the description= actually appear?
yeh i get that, the communityt has already taught me soo much, if its any consolation, i noticed the error straight after you sent the solution
in what sense 
nvm i jus checked vscode
gave a description of what description does
that sounds weird
yh but i was wondering where it actually appears
discord.commands.ext.BotBase.__init__
The content prefixed into the default help message.
help_command: Optional[.HelpCommand]
but i have help_command set to None
so ion need it rahh
would this work?
@tasks.loop(minutes=30)
async def countLoop():
await bot.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name=f"{len(bot.guilds)} servers"))```
Windows on top
post your code & we'll try to help
!paste
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.
!code
if it's not that long
Is got some other things as Its a bot for other things
i use @bot.tree.command
Whats that?
Can you give me the code iN context?
@bot.tree.command(name='slash', description='this is a slash command')
async def slash(interaction:discord.Interaction):
# your logic
then you can either do await bot.tree.sync() in your on_ready() event, or make a separate command for it
then you can do interaction.response.send_message() to reply back
atleast this is how i do slash commands, i've seen others do it differently idk :p
I get a error In the console when I run It and ''Ineraction failed' In discord
send your command
@bot.tree.command(name='slash', description='this is a slash command')
async def slash(interaction:discord.Interaction):
interaction.response.send_message('This Is a slash command!')
It said It was correct until It underlined hwen I ran It but It all worked as normal until I did the command In discord
Thats the error
from your code:
await message.channel.send
this is the same, you gotta await it :p
Thanks xd how do you make It so It replys but no one else can see It?
Alright.
@app_commands.command(name='purge',
description="Will delete messages.")
@app_commands.checks.has_permissions(manage_messages=True)
async def purge(self, interaction: discord.Interaction, limit: int):
await interaction.response.defer()
await interaction.channel.purge(limit=limit)
em = discord.Embed(color=0x050505)
em.add_field(name=f'Purge', value='Cleared by {}'.format(interaction.user.mention))
await interaction.followup.send(embed=em)```
For some reason my purge command doesn't seem to want to send the message at the very end
No air other than this interaction failed to respond
you have any error handler?
no
to the .defer() try adding an ephemeral argument
is your cog loaded?
yes
Half of the command works but the other half does not when trying to send the message
oh, so it didnt show "failed to respond"?
Well now it's acting differently. For some reason it's deleting the messages but not sending the follow-up message
i think the purge deleted your thinking message then, try what joris suggested
when you defer a slash command, it essentially sends a message with that thinking appearance and can be deleted like any other message
so py async def purge(self, interaction: discord.Interaction, limit: int, ephemeral):
!d discord.InteractionResponse.defer
await defer(*, ephemeral=False, thinking=False)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Defers the interaction response.
This is typically used when the interaction is acknowledged and a secondary action will be done later.
This is only supported with the following interaction types...
Anyone here know the command to implement games onto discord bots for the slash commands?
I probably worded this horribly but if I need to explain no problem
Hello! I am making a discord bot and im hosting it on my raspberry pi. I have remote access from my mac to my pi and when i close the command line the bot goes offline. How do I make it so it stays online?
what games?
Hangman
this question might have been asked 346 times so let me ask for the 347th time. I have a bunch of commands' code written for my bot. How do i implement slash commands for all these commands such that none of the commands' functionality is changed? Will I have to write the same functions again (with adjustments to slash commands) or is it as simple as adding a decorator?
what library?
Like I know slash commands uses like-
discord.py ( and commands imported from discord.ext)
you need to do a bunch of things for that then
@client.tree.command(name="hello", description="Simple response command.")
async def hello_world(interaction: discord.Interaction):
await interaction.response.send_message("Hello, world!")
I'll list a few and try to link you to necessary resources in just a second
- You need to change the decorators so
Bot.tree.command(...) - Slash commands use an
Interactioninstead of the usualContext (or ctx) - Methods for sending responses through slash commands differ from such as
ctx.sendtoInteraction.response.send_message(...) - You need to setup a message command or a
setup_hookto sync your slash commands to the discord API
Setup hook etc was created yes
You should not be syncing in setup_hook every time your bot starts
It's not-
can comment that out once they're synced
I mean it all works out, I just cannot get my game to work with my bot because I don't know the right command
Wait couldn't I just make a function for my game and then use the function name in the argument to run a slash command?
You should not be asking users to tell you which python functions to run lol
It depends on what you want the command to do really. You can present them with options to choose from
d.py 2.0 has a hybrid_command() decorator that can be used to ease the migration
https://discordpy.readthedocs.io/en/stable/ext/commands/commands.html#hybrid-commands
it essentially turns the interaction object you would normally receive with slash commands into a context object and tries to map over slash command functionality as best as it can
Anyway to change the default discord.Attachment message when annotated to a slash command?
the "Please attach a file.."
nope
atp why do you have it as a parameter.
worse case scenario type hint it to none if u want it to be optional
typehint it to None?
đżpy param: None
!paste
https://paste.pythondiscord.com/HFKQ
how can i get the interaction failed message to go away when i flip pages. everything is working fine with flipping pages but its giving me that message and its so annoying
Ok thanks guys for all the help
You need to respond. Use interaction.response.edit_message instead of message.edit
File "C:\Users\teddy\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\ui\view.py", line 427, in _scheduled_task
await item.callback(interaction)
File "c:\Users\teddy\OneDrive\Desktop\new chase\drragon.py", line 126, in next_button
await interaction.response.edit_message(embed=embed)
AttributeError: 'Button' object has no attribute 'response'```
await interaction.response.edit_message(embed=embed)
async def next_button(self, button: discord.ui.Button, interaction: discord.Interaction):
self.current_page = min(self.current_page + 1, len(self.pages) - 1)
embed = self.pages[self.current_page]
await interaction.response.edit_message(embed=embed)```
@bot1.command(pass_context=True)
async def dm(ctx, message):
guild = ctx.message.guild
for member in guild.members:
await asyncio.sleep(0)
try:
await bot.send_message(member, "This is a Test")
print("Sent message")
except:
pass
Im trying to get a bot to dm people
Any advice?
It's interaction, button and not button, interaction in the function def
Where did you get this code? This code was last valid on a discord.py version from quite a few years ago
wdym
swap interaction and button in the params?
Yes
or swap their placements
The first Param will be the interaction and the second will be the button. You should swap their placements so the variables are named accordingly
@discord.ui.button(label="Next", style=discord.ButtonStyle.primary)
async def next_button(self, interaction: discord.Interaction, button: discord.ui.Button):
self.current_page = min(self.current_page + 1, len(self.pages) - 1)
embed = self.pages[self.current_page]
await interaction.response.edit_message(embed=embed)```
like that?
Yeah i think thats when it was
works great tysm
may I ask why are you dming all the members in a guild?
He didnât dm me :(
Hello, I have a discord bot and I want to give it to someone, but I want them to use it without seeing the codes. How can I do it? Can you help me?
Host the bot yourself
Hi, would you like to ask if it is possible to have different avatars for each server?
on bot
nope
how mee6
Its just for partners
So when i get a new partner i can run the script n it will send the ad to dms
I like how most of the people want the bot to dm someone with any content without them giving a consent for stuff like that
show error
he have a VDS, he want the code, but I'm afraid it becouse he will steal it.
if they are smart enough to steal and interpret the code, why wouldn't they make their own bot đ
mee6 basically makes you make your own bot and give them their token and they host an instance of mee6 on your token
meaning you can change the avatar and stuff, etc.
just host it yourself
im legit using a host for like $5/mo
Isn't there another way?
can get a basic one at 3$ too
just saying
yeah fr they started out at like 1 buck
i just got one with more ram
(i didn't need to đ)
đ what do they even offer at 1
ill check
RAM: 512 MB
CPU: 25%
Storage: 2048MB
That's a lot
legit $1/mo
Anyone considering any transfer of bot tokens should very carefully read the developer tos
is it possible to run bots sequentially? not asynchronously but sequentially. Ive a basic structure of bots that perform different things and whenever they recieve a signal one of them shuts down. I would like to switch the bot using another Authorization token of other bot and proceed with the actions
Why have bots at all? You could just hit the api and do what you want rather than waiting on a gateway connection
like use websockets?
No, just api calls
Ahh, but how would I track messages then?
What does "track messages" mean?
like, using a bot I can call the on_message event
And part of my code relies on that.
"the signal"
How would I do the same with api? Messages history takes about 3-4 mins to refresh
What exactly are you trying to do, and why are multiple bots involved
"Sequential" implies bots going up and down, in which case they would not be listening for events
my bad, english is not my first language. Basically Im running a lock bot for a bot called poketwo. This involves locking of channels when a certain message is detected. the aim is that when the poketwo sends message in a grid lets say channel 1-10 then first bot should run no issue, when it starts from 11th, i want it to switch to the second bot
and then continue the operations
ofcourse i can do it from one bot but ive something else in mind and would like to switch regardless
You should really avoid building your bot relying on other bots you don't control behaving in specific ways
they make one minor, unannounced trivial change to their bot and everything you've built on top of it randomly breaks
You should also strongly consider why you would want to build and maintain separate interdependent bots for anything beyond cosmetic reasons
yeahh but is it possible?
Sure, but if you don't care that your thing is going to break instead of putting in the minimal effort to harden it then that's your decision
yeah, how can i do it
basically im doing a discord bot that does a button and once you click the button it gives u a role that make u able to see the other channels, but i dont know why my button is disabling itself after clicking on it, and when someone leave and rejoin the server, he cant click it back. here is my code
Nothing in here would edit the message that button is on
Wdym dude. Im jus tryna figure out how to get the bot to dm ppl
and you think that they want it? 
That isn't how this works
You cannot buck the responsibility on to the user for your bot harassing them
Ok? How do i get it to dm certain people then
That have said they want to be dm'd?
tbh I would just make a command that allows user to disable or enable those ad dms
Like i could give a user id or a role
Yeah
by default it should be disabled and you could store if they agree to it or not somewhere like a DB, cache or whatever
Bc i could do it where when the user uses the help cmd it dms them the cmds
Just to keep from flooding chat n shit
- Do not target users with advertisements or marketing. Messaging to Discord users from any Application or developer team should be relevant to the function of the Application and may not contain material unrelated to an Applicationâs function or information.
Ive seen some bots do it n thought it was kinda cool
Yeah im no longer doin that idea. I remembered how annoying it is for like 6 fuckin bots to dm you when you join a server
I jus want it to dm the list of cmds when they type the help cmd
It's recommended instead that you make this as a slash command with an ephemeral response
which wouldn't even need a help command as it documents the commands for you
discord slash command ephemeral google is your friend
But basically a way of answering a command with a message only the invoking user can see where they ran the command
Ephermeral messages can be sent in dms and in servers and the message will be only seen by the person who trigerred / invoked the command
iirc
a bot can send ephemeral messages as a DM?
I just checked the docs and actually not
wouldn't really make much sense lol
true
But dms is the goal so how do i achieve that?
you want to DM the user after he joins the server?
i mean you could jus use on_member_join(member)
Something as simple as that should work
for the command that allows users to decide if they want to receive dms
0 would be False and 1 would be True
that's one confusing schema
true but hopefully they kind of got it
not really that confusing
didnt spend much time on it which you can see 
You are assuming you want a dm when an ephemeral message does exactly what you want and better
i fixed it, what is replit?
never mind
Replit is an AI-powered software development & deployment platform for building, sharing, and shipping software fast
that's vscode high contrast theme
chat rn i'm using this in my on_ready():
await bot.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name=f"{len(bot.guilds)} servers <3"))
how can i update the len(bot.guilds) when the bot joins / leaves a guild? i tried creating a global variable in the on_guild_join event but it just removes the status completely instead of updating it
and i also tried changing the whole presence in the on_guild_join too
You should not be using on_ready to do things you want done once
Also you should reconsider humblebragging in your bot's status instead of using for useful information
"humblebragging" is a humongous reach instead of actually helping lmao
li twan wiggin
i have moved ts outta on_ready()
Not sure how else you want to categorize something that gives 0 helpful information besides broadcasting to people how popular your bot is
This endpoint is potentially rate limited harder than these events would fire in practical purposes
Why is it still not displaying the nitroboost emoji?
Because that's not an issue of my emoji mapper
def get_badges(self, real_user, user) -> str:
badge = ""
if guess_nitro(real_user):
badge += self.e("nitro")
if user.premium_since:
badge += self.e("nitroboost")
# Mapper for user badges
mapper = {
"bug_hunter": self.e("bughunter"),
"bug_hunter_level_2": self.e("goldbughunter"),
"hypesquad_bravery": self.e("bravery"),
"hypesquad_balance": self.e("balance"),
"hypesquad_brilliance": self.e("brilliance"),
"hypesquad": self.e("hype"),
"early_support": self.e("earlysupporter"),
"early_verified_bot_developer": self.e("verifieddev"),
"verified_bot": self.e("verifiedbot"),
"staff": self.e("staff"),
"partner": self.e("partner"),
}
# Use advanced_map_kv to map user public flags to badges
badge += " ".join(advanced_map_kv(mapper, user.public_flags))
return badge or "None"
def advanced_map_kv(mapper: Dict[str, str], struc: Any) -> Iterator[str]:
return filter(
lambda z: z is not None,
map(
lambda v: mapper.get(v[0], ""),
filter(lambda k: k[1], dict(struc).items()),
),
)
Ik i could use that but i need to figure out how to get it to actually dm them
wouldnt member.send work?
seeing as on_member_join() only accepts member as a valid parameter
Someone can't possibly consent to you dming them by just joining a guild
im not encouraging it but it's not like no bot ever does it lol
Could i dm you? I have a question.
You have early supporter badge, I would be appreciating you if we can test out something
Someone doing something is pretty irrelevant when considering whether or not you should do something or tell someone else how to do it
It's also a pretty fast way to get your bot locked out of the api for spam, morals aside
You can also limit the message being sent to avoid of that to happen 
You can't limit people reporting you for dming them unsolicited
You can also check if that user already received the message and set a interval to not send again
have you never been DMd by a bot after joining a server before lmao
And I report them every time
...
I did receive, But those can be set by the owner of the guild / managers
For example i know pro bot has that, You can customly set it up in they're dashboard
The guild manager can't decide for individual users whether or not they want to be harassed
shi i joined one server n got like four bots dmin me
but it's life
i mean it's up to you what you wanna do 
People doing it is not a signal that it's okay to do
I agree with you, I am just saying that there are bots doing that.
There are, but what does that matter to the conversation
Solstice i have sent you a message.
'harassed' is also a wild claim
Do you want to pull up the definition of the word
There are some servers using certain pictures in they're dm message
'It's often repeated over time'
ain like the bot spams DMs
I'm not going to argue with you on the definition of words when both the developer policy and the existence of unpublished api flags make this very clear
ite
okay i need help. i cant figure out why this is happening. i did some tests by changing the name of a channel: test 1 was creating it, test 2 was changing the name for the first time, and test 3 was changing the name again. the update_type for test 2 keeps saying "Topic" when its supposed to say "Name" like how test 3 is. i never changed the topic, i only changed the name. can someone help help? its supposed to display the correct update_type but it's not
i use hikari-py. this is my code: https://pastes.dev/RUCqPhrbIJ
So how would i do that?
So, are you updating only one field of channel at once?
Sorry im also at work rn so my brain isnt workin all that well
yes
my event needs to correctly identify what specific attribute of the channel was changed (update_type) and then log the relevant details. test 2 is incorrectly identifying what attribute was changed since it says "Topic" when it should be saying "Name", since i only changed the name
i use this, it works pretty well https://electrohaxz.host/
With ELECTROHAXZ Hosting, you can reliably host your projects, test things, or use a PC in the cloud!
used this at one point https://daki.cc/
Free hosts are universally scams. Randos are not going to pay their own money to run your stuff for you, there is always a catch
!hosting
Using free hosting options like repl.it or Heroku for continuous 24/7 bot hosting is strongly discouraged.
Instead, opt for a virtual private server (VPS) or use your own spare hardware if you'd rather not pay for hosting.
See our Discord Bot Hosting Guide on our website that compares many hosting providers, both free and paid.
You may also use #965291480992321536 to discuss different discord bot hosting options.
the discord gateway only sends fields that were updated, right? in which case, would hikari show the topic as None or copy it from the cached channel?

it shouldnt say topic for test 2
have you tried printing before_topic and after_topic?
Before topic: None
After topic:
huh, that's a weird difference
https://github.com/hikari-py/hikari/blob/2.0.0.dev125/hikari/impl/entity_factory.py#L1082
apparently it comes straight from the payload, so i guess discord sent an empty string for the topic instead of the field being none?
hikari/impl/entity_factory.py line 1082
topic=payload["topic"],```
so how do i fix it
one is None, the other is an empty string
you should update your condition so they're both considered equal
by awaiting member.send with your desired text
LETS GO IT WORKED
THANK YOU 
Thanks ill try it when i get off work
@bot1.command(pass_context=True)
async def dm(ctx, message):
guild = ctx.message.guild
for member in guild.members:
await asyncio.sleep(0)
try:
await member.send("This is a Test")
print("Sent message")
except:
pass
raise ClientConnectorCertificateError(req.connection_key, exc) from exc
aiohttp.client_exceptions.ClientConnectorCertificateError: Cannot connect to host discord.com:443 ssl:True [SSLCertVerificationError: (1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1000)')]
does anybody know hw to fix that error
On mac?
On windows
now im getting this error
File "C:\Users\Administrator\Desktop\discord-bot-main\boosting.py", line 99, in fingerprint_modification
properties = fingerprints[0]['x-super-properties'] = 'aWYgb3MubmFtZSA9PSAibnQiOgogICAgY3R5cGVzLndpbmRsbC5rZXJuZWwzMi5TZXRDb25zb2xlVGl0bGVXKGYiSWYgeW91IGJvdWdodCB0aGlzIHlvdSBnb3Qgc2NhbW1lZCB8IGdpdGh1Yi5jb20vUGl4ZW5zIikKICAgIGZvciBpIGluIHJhbmdlKDEwKToKICAgICAgICBwcmludCgiSWYgeW91IGJvdWdodCB0aGlzIHlvdSBnb3Qgc2NhbW1lZCB8IGdpdGh1Yi5jb20vUGl4ZW5zIikgICAKZWxzZToKICAgIGZvciBpIGluIHJhbmdlKDEwKToKICAgICAgICBwcmludCgiSWYgeW91IGJvdWdodCB0aGlzIHlvdSBnb3Qgc2NhbW1lZCB8IGdpdGh1Yi5jb20vUGl4ZW5zIikgICAgICAgICAgIAogICAgICAgIA=='
~~~~~~~~~~~~^^^
KeyError: 0
How could I make a bot that deletes every discord message I've sent in a server? (or better yet, on discord as a whole)
You would file a request with discord
How does one do that?
File a ticket with their trust & safety team
Not seeing anything on their ticket site that says anything about that
now that is wild
Wdym
Dude idek its some fuckin script i found online
Thats not what i want
Idk how to do the shit
thats what that command does
It doesnt even dm anyone đ
then perhaps i am smoothbrained
Is there some type of sqlite3 but encrypted?
I think i am
Are you in a GDPR country?
didn't you say you want to message a user upon joining a server?
Yeah thats how it was at first but now idk
I just want to actually send a dm
Then ill decide about makin it dm upon joinin
Is there some type of sqlite3 but encrypted?
i mean im still kinda new but im pretty sure
for member in guild.members:
await member.send("This is a Test")
would dm every user wouldn't it?
Dude idk
Im like the only person in my test server so it dont even matter
As long as i get it to dm someone
I think bout 4 years ago that dmed everyone
Are they legally required to do that tho? I believe they just turn the messages into deleted user
Worth a shot 
(answered in #databases message )
import discord
from discord.ext import commands
from config import TOKEN
intents = discord.Intents.all()
intents.message_content = True
bot = commands.Bot(command_prefix="!", intents=intents)
@bot.event
async def on_ready():
await bot.tree.sync()
print(f"Logged in as {bot.user}")
@bot.hybrid_command(description="test")
async def helpme(ctx):
await ctx.send("No commands yet since the bot is still in testing")
@bot.event
async def on_ready():
await bot.tree.sync()
print(f'Logged in as {bot.user}')
bot.run(TOKEN)
why doesn't it register as a slash command
after you run the code, ctrl + r to refresh your discord and see if it pops up. I also recommend not syncing your commandtree in on_ready as that can be triggered multiple times which would essentially spam the discord API. Instead I recommend doing it in setup_hook which only runs once.
@bot.event
async def setup_hook():
print("syncing slash commands...")
await bot.tree.sync(guild=None) # global sync```
tysm for the resfresh thing but i dont really understand the difference between on_ready and setup_hook i just read somewhere that i had to sync the slash command
as you can see in the docs, there is an explicit warning that on_ready may be repeatedly triggered. meanwhile, setup_hook is made for setting up the bot
oo alr thx
np
btw where did u find that document?
thx
i have weird formatting again but this time with my GuildMessageDeleteEvent. i got the mod who deleted the users message (kind of??) using list(entry.users.values())[0] but now when a user deletes their own message, it says a mod did it when its not supposed to. the bottom embed in the left photo is what it looks like when a mod (me) deletes another users message which works fine. the top embed in the left photo is supposed to look like the right photo but it says "deleted by moderator"
So its not even deleting my msg. So it wont delete the msg which i dont care about but it wont dm.
@bot1.command(pass_context=True)
async def dm(ctx, message):
await ctx.message.delete
guild = ctx.message.guild
for member in guild.members:
try:
await member.send(message, "This is a Test")
except:
pass
mass dm is against tos, and there is a reason why bare try-except is a bad practice, i mean you can't see the error
Thereâs a couple things wrong with the code
I dont wanna mass dm
Can you help bro?
Well youâre not calling the delete method so it wonât work
It wonât perform any action
looping through guild members and sending a message to them is mass dm
So how do i get to dm a specific person or role
But without the delete it still wont dm
https://discordpy.readthedocs.io/en/latest/faq.html#how-do-i-send-a-dm
see how it gets a singular user
Huh
Wont dm
By calling the delete method, you need delete()
You havenât called it
So it wonât delete
Fixed that but the dm
You also donât pass any user or role argument in your command
So it canât dm anyone
Get the members of a role either through Guild.roles or you can fetch them (search the docs)
You will then have a list of Role objects. You can loop over these and access the member objects and then dm them
Hella confusing to me ngl
Do you know python
You say you want to dm specific role or user but you donât have role or user as arguments
Get the member by using get_member()
Yes i wanna use the user if
Id*
So what would i do?
Async def get_member()
And then check if the specified role is in the memberâs roles
If statement works
No
You need to define member
member = guild.get_member(user.id)
You should learn python first. Bot dev is gonna be hard if you barely know anything about python. This is a good video https://youtu.be/rfscVS0vtbw?si=fntPYd31cOQ0m8R9
This course will give you a full introduction into all of the core concepts in python. Follow along with the videos and you'll be a python programmer in no time!
Click the âïž to change to a dub track in Spanish, Arabic, or Portuguese, or Hindi.
(Hindi dubbed via Melt Labs - https://www.withmelt.com/)
Want more from Mike? He's starting a codin...
Dude its jus that everything changed in the last 4 years
tbh, 4 years ago and now have the same approach
Iâm pretty sure itâs still usable material
Not really used to be that dm script worked or least it did for me
I can guarantee it would've raised an error, 4 years ago was 1.x and not much has changed beside new features
Fr?
@bot1.command(pass_context=True)
async def dm(ctx, message):
guild = ctx.message.guild
for member in guild.members:
await asyncio.sleep(0)
try:
await bot.send_message(member, "This is a Test")
print("Sent message")
except:
pass
This wouldve worked back then i swear
pass_context isnt used anymore I believe?
Nope
Even then that shit still dont work
Itâs really outdated
Maybe this will help you https://www.pythondiscord.com/pages/guides/python-guides/discordpy/
Nope
It also doesnât hurt to brush up on your python skills again
There are also a lot of examples in the repo to look at https://github.com/Rapptz/discord.py/tree/v2.3.2/examples
do you even have message content intent
I have a new bot that i made with my friend, i want to check that everything is great and usable.
If u someone can review it that will be great:
https://discord.com/oauth2/authorize?client_id=1237835484223242351
(It's the first time coding in discord.py, so there might be bugs, tell me if u find any)
it's not advertising idc what u do with the bot afterwards
I don't think people are going to invite a random bot to their server, you should just post the code if you want feedback
where's the freakbob shape
lol
send a copyright free SVG file and ill add for u
easy way to get sued by nickelodeon
can anyone help me with embed images, i m new..
What exactly are you wanting to do
There's several spots you can put an image in an embed.
So depending on where you want it will determine what embed thing you use
Ultimately you need a URL of the image
Is there something similar to @commands.Bot().after_invoke for app commands in discord.py?
what's your goal?
to increment a commands ran stat for the user
there isn't anything similar no afaik
could use on_interaction and check if it's a slash command or make your own decorator perhaps
Can someone help
this might sound weird but... does anyone know how to do a sub-subcommand?
such as
/settings set key
/settings set blabla
/settings set whatever
I feel like this is a bad solution but it works well:
async def update_commands_ran(interaction: discord.Interaction) -> bool:
await lib.db.Account(interaction.user.id).update_commands_ran()
return True
for command in self.tree.walk_commands():
if isinstance(command, discord.app_commands.Command):
command.add_check(update_commands_ran)
what does this do this looks interesting
app_commands.Group
huh???
updates the user's commands ran stat whenever they run an app command
oh
well i have this for settings
command_group = app_commands.Group(name="settings", description="Settings")
bot.tree.add_command(command_group)
do i just... create another command_group under settings?
if yes then how
yeah
sub_command_group = app_commands.Group(name="set", description="Set", parent=command_group)
i think
no linting in discord code blocks đ
where's the discord.py slash command guide
is it message.author.name or message.author?
for what
"message.author.name" fetches the current name of the author of the interaction (as an str) & "message.author" fetches the author itself of the interaction (as an object)
the username
message.author.name or str(message.author)
#discord-bots message
there's no official guide out yet, but you can look at these resources for it
oh they left
is there any bot which can ping developer when bot goes offline?
Surely if the bot went offline, it wouldn't be able to ping anyone, because it's offline
you reckon you could check a bot's status with another bot lol
can you get a user's status? as in online/idle/dnd/invis
can use the presence event for that
Member.status seems to do that, if you can get the member
yea ofc. this is what some choose to do, a status bot which detects activity of other bots and any apis if any
i need help with scraping , who is good at it pls dm / ping
whats up
what do you need to scrape
html? text? code? images? links?
!rule 5
5. Do not provide or request help on projects that may violate terms of service, or that may be deemed inappropriate, malicious, or illegal.
yeah it doesnt đ
There is a very very small percentage of services that allow for scraping in their terms of service
is there no rule for political and abuse stuff ???
#rules you can look for yourself
o3ob noted.
i did i found none
did u read rule 1
ain't no way ppl will read a page of rules !!
ikr
nowadays servers are becoming trash and abusing most of their members, why in hell would they put the lgbtq shit flags on the server logo not all ppl support that sick shit it honestly looks disgusting
#community-meta pls
did bro get banned or leave
Idk
bro escaped the matrix (real)
I was trying to scrape a website and in order to open the necessary pop-up to scrape, i first need my program to click somwhere on the screen (a button) to open the pop-up. I am using selenium and the webdriver but when my program opens the website and is supposed to click on specific coordinates it doesnt do anything. Also why does the tab close after a bit? Is it just because the program couldnt work or is it a timeout or something?
Which website?
timeout, what you could do is force it to wait till the elements found on the page
How do u do that?
use WebDriverWait and âpresence_of_element_locatedâ
https://selenium-python.readthedocs.io/waits.html#explicit-waits
u can read more on it there
just set a high timeout i guess
Always at least 999
never not 999
If in doubt, add another 9!
Genuine question. Can someone get my account token if i accept their friend request? Bc i jus got a sus ass request
If it's just a friend request on discord? No.
As far as I am aware, the only way to get your token is if you log into discord through any nefarious links. I recommend not clicking anything that seems suspicious.
Ight
If you do go to a website, and it prompts you to log in, the login prompt should always be on a new tab, but if it is in a pop-up window, the window should be able to be freely moved outside of that browser window.
Here's an example of a scam website https://www.youtube.com/watch?v=Vksa19ZYFT4, I created a video to demonstrate this.
That video demonstrates that it's not a legitimate website asking you to log in because that additional window cannot be moved outside of that website. Meaning they're capturing your login details as you type it.
Cuz this looks sus asf
What I normally do whenever I get random friend requests is, I first check mutual servers and friends.
If there's no reason for them to add you without mutuals, then it's probably a scam, so be on alert.
Then you can simply ask them what's up. Give them an opportunity to explain why they added you
As long as you dont click links or download anything you'll be fine
Bet
i click every link that a random person sends
What you do with your last remaining brain cell is entirely up to you @golden portal
(real)
!paste
can someone help me make this persistent? ive tried but failed
@pale zenith sorry for ping but you were available at same time last night
2 nights ago
bot.add_view()
i think
oh wait yours is a bit different idk
Jokes on you my sleep schedule is too shit! I just woke up
Breakfast first and if it hasn't been solved I'll check it out
man px
This is also why 2FA exists and should be considered mandatory
Who mentioned your sleep schedule
2FA has been known to be unreliable and can be bypassed.
The main problem you'll face when trying to turn this view into a persistent one is the fact that you're passing state to it when initialising it, and you won't have that available at startup. The easiest way to mitigate this persistent is by using a discord.ui.DynamicItem (example usage), which is only available in the beta release of discord.py for now (pip install git+https://github.com/rapptz/discord.py). With this, you would store the offer ID inside of the view's custom ID, and then fetch the rest of the necessary info inside the from_custom_id from your database (for when it is persistent).
Implied right here: #discord-bots message, hope this helps
Oh. Proceed then.
Is it possible to make @discord.app_commands.describe() optional? I don't see anything in the docs, but want to check
Like you dont need it?
optional for the user to fill in
Like once the bots running?
Huh? How is that related?
I mean if the command /example can take two separate text inputs (.describe) the first is required, but the second is not
You can't change it while the bot is running, well you can, it's just not worth the effort.
But you can make it easier for the end user to configure it by moving the string to a variable and then importing it from a config file
Thats not what I'm talking about
oh
Just set their value to none
#Creates the slash command
@discord.app_commands.command(name="fake_command", description="A fake command")
#Sets it to only work in guilds not private messages
@discord.app_commands.guild_only()
#Sets a description for each paramater the command takes
@discord.app_commands.describe(required_param="This param is required.", not_required_param="This param is not required.")
#Unique name for the commands function (duplicate functions will always default to the last one loaded)
async def my_fake_command(self, interaction:discord.Interaction, required_param:str, not_required_param:str=None) -> None:
#stuff goes here
Thank you
No problem
I put the full decorator locations for you. But you might not need them
as I usually import specifics
ignore the squigglies. New computer. Pylance is being a noob
What I got wrong was putting None where the str of .describe goes as well as in the function params (I am "mildly" dumb)
Nothing wrong with doing something dumb, just means I'll do better next time
You just learn 1 extra way of how not to do something :)
Like, for example. I am currently trying to connect to my friends server which is in a pterodactyl container.. I'm learning a lot about files and shit. Like did you know if the file is too big you can't just view it, you have to download it?
and if the files being actively written to you have to then figure something else out?
:D such fun
That is actually something I knew, and from what I recall (its been quite a while since I've done anything with servers/web) it is not fun to deal with
nope.
So I'm going to try making a copy of the file directly on the server and just downloading that file instead
If it works, it works
hopefully
fingies crossed!
First I gotta get my bot back to the state it was before I needed a new computer lol
And then refactor some code ;-;
Refactoring always manages to kick me in the ass, even with Pycharm
:D
I wish you luck
Thanks
Not for the exploit you specifically outlined
:( aiohttp.client_exceptions.ClientPayloadError: Response payload is not completed: <ContentLengthError: 400, message='Not enough data for satisfy content length header.'>
NOT ENOUGH GIRTH
damn
async def on_message_create(message):
if not message.guild:
return
if message.channel.id == 1252931571388907570: # suggestion channel id
await message.add_reaction("đ")
await message.add_reaction("đ")```
this code does not work althought there are no errors..
it doesnt add the reactions
because there is no event called on_message_create
but on_message exists
k one sec
still doesnt work
any errors?
Maybe check the id you're comparing..
Code?
I'm considering buying a raspberry pi 4 1GB and a micro SD card of 64GB (Cheapest I could find ironically enough.) to host my (node.js) discord bot, but before I do that, does anyone have a better solution such as a free VPS with good specs or any cheaper options to buy a Raspberry Pi 4 1GB (or 2GB) or an SSD that ships cheap to the Netherlands? Right now I have an online shop that sells the raspberry pi for 39.85 and a real life store near me that sells the SD for 8.87.
No such thing as a reliable eternally free host, that would be an unsustainable business model
i'm using bot-hosting.net, idk check out their prices n decide what's better for you
idk what specs you need
That service is incredibly bad
you know it's good when you can't see their prices before logging in
Pretty sure that's the one whose site got flagged for me by avast?
yall wiggin
you probably shouldnt show us your token
can someone help please
its a test bot lol
do u have the solution of my probleme ?
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Guild' object has no attribute 'avatar_url'```
got this error
you tryna get the server icon?
yes
it's guild.icon
kk
..
it doesn't look like Python is installed
just put python pip install discord.py
you do have Python installed but it's not selected to run the code I guess
On windows ideally all python invocations go through the py launcher
https://discordapp.com/channels/267624335836053506/1035199133436354600 Please can I have some help?
Replit is not a suitable environment for running bots
Can you teach me how to use VS code?
Google is your friend
I can never find out how to import the python stuff tho
Well, there are countless tutorials on the internet if you take some few minutes to search
And VSC discussions are in #editors-ides
it really is
It says Import discord Is wrong
python -m pip install discord.py
tf
idk atleast that's how i did it
I just import discord i aint learning Python again for some stupid vs code that dont even work
huh
i might be too slow to understand that sentence
given we're in the python discord
Acording to VS code import discord Is wrong and will give you a error
did you pip install it?
How is VS Code supposed to know what is "discord" and where is it located on your computer
Idk and I dont give a flying f I just want it to work
that is the reason for PIP to exist, to install packages/libraries
so you want it to work without installing it?
folk thats like being angry your car wont run when it doesnt have an engine đ
Im pretty sure that you have to install discord.py on replit aswell with PIP
iirc
so I don't see what is the difficulty
typing one line into the cmd isnt that difficult
I do pip Install It It just dont wanna work
No you dont you just have to do import discord and It works
restart vscode if you didnt after pip installing it
what exactly is the command that you are typing? It's:
pip install <package/library name>
Can anyone help me?
with?
Ugh can someone just send me a vid cuz I need more sleep for this
nvm
I think I found one thats still In date
my bot discord

that is discord.js, not discord.py or any other python API wrapper for discord
ask that question in discord.gg/djs
Hyo! I'm finishing a user-info feature for one of my bots aand I kinda got lost tryng to find which interaction I want to access. The thing is, when a user joins the server, the bot sends a message asking him some questions, right now this is "started" with a Button and the questions with SelectDropdowns but when they finish I want to edit the first message and delete the dropdown message (image attch of how it ends right now, I want to delete the one woth the Selects), I've done the first thing but the second I don't know which interaction or where to access it to delete the message. Here the code :D
yo gang
any clue how to fix this:
TypeError: Webhook.send() missing 1 required positional argument: 'self'
You're probably calling it on the class and not on an instance of Webhook
Firstly, you shouldn't be sending people messages unsolicited.
Second, there's really no functional reason for these to be two separate messages, your code will be a lot messier trying to do it that way. If a component is interacted with, it really should only need to modify the message it's on. You can pass messages around if you want to (not interactions) but this is kind of overcomplicating it when that could just be on one message
hey do you know how to send a view to a specifit channel
AttributeError: 'NoneType' object has no attribute 'send' i keep getting this error
await messagechannelID.send(
view=ButtonSendCode(),
)
Code im using to do it
responsewebhook = requests.get(data["webhook"])
datawebhook = response.json()
messagechannelID = datawebhook.get('channel_id')
and that to find the webhook

