#discord-bots
1 messages · Page 364 of 1
the other instances of that line of code simply edit the original message though, im not sure why this one specifically is giving me issues
and the original message is still present when that line runs
like if we were playing a card game: i have to wait for you to play before i can play my card. but what you’re doing is the same as me playing my cards before you play your turn
!code throw your code in a pastebin and tell me what it says
uuuh the whole thing is like over 250 lines
show the view thats giving you the error
you dont have to put the whole thing in lmao
So i first send the message up here:
await ctx.send(embed=embed, components=components)
then have 3 occurrences that all function correctly of:
await interaction.followup.edit_message(
interaction.message.id,
components=components,
embed=embed
)
then the block of code causing issues is:
if interaction_params[0] == "Dungeon":
profile = await get_profile(interaction.user.id, db)
index = int(interaction_params[1])
dungeon = self._dungeons[index]
difficulty_embed = LocationsUserInterface.dungeon_difficulty_selection_embed(dungeon)
if index in profile["dungeons"]:
has_diff = True
else: has_diff = False
components = LocationsUserInterface.dungeon_difficulty_selection_components(index, interaction.user.id, has_diff)
await interaction.followup.edit_message(interaction.message.id, embed=difficulty_embed, components=components)
if i defer it fixes it but then it gives me an interaction has already been responded to prompt anytime anything goes off
i cant read this when its in codeblocks cuz im on my phone. thats why i said to use the pastebin
can someone help me make a ticket system
oop sry, english is not first language, i think i see
need more info than that
nps dw abt it 👍🏽
just wanna make sure you get the best help available
pasted
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.
does ctx.send even take components?
it just shows "this didnt work" or something like that
!d discord.ext.commands.Context.send
await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sends a message to the destination with the content given.
This works similarly to [`send()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Messageable.send) for non-interaction contexts.
For interaction based contexts this does one of the following...
when i click the button
it sends the components and embed correctly yes
whats your dpy version?
!traceback
Please provide the full traceback for your exception in order to help us identify your issue.
While the last line of the error message tells us what kind of error you got,
the full traceback will tell us which line, and other critical information to solve your problem.
Please avoid screenshots so we can copy and paste parts of the message.
A full traceback could look like:
Traceback (most recent call last):
File "my_file.py", line 5, in <module>
add_three("6")
File "my_file.py", line 2, in add_three
a = num + 3
~~~~^~~
TypeError: can only concatenate str (not "int") to str
If the traceback is long, use our pastebin.
there literally is not a error code
if theres no error in terminal then just defer the button 🤷🏽♂️
gambling
yeah?
plis help me with slash commands
lmao
Nice interaction check 😃
@viscid hornet
THX
I promise you that I will get you a nitro boost and give it to you as a gift.
read what i say next time 👌
nah man. boosts dont mean anything but i appreciate the offer 🤷🏽♂️
nitro boost
you set it
the same way you would with a command prefix or with a db pool
just a teeny weeny bit 🤏🏽
ily
i think i figured it out thank you<3
👍🏽
😭🙏🏽⁉️
topggpy
and some other libraries
ah ok
did all the libraries install fine?
yes
Bro im going to fkkkkkin ballistic, every video garbage, Embeds was so easy to do but now when it comes to slash commands, idek how to start, where to start, I need help brotha
!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:
oke
it doesn't translate perse it just passes the command name params etc to the translator for which u need to get the translated text from files like pot files
Yeah I found that out lol
how im create a avatar slash command: ```py
import discord
from discord.ext import commands
from discord import app_commands
class Avatar(commands.Cog):
def init(self, bot):
self.bot = bot
@app_commands.command(name="prof", description = "Get avatar")
async def prof(self, interaction):
await interaction.response.send_message("This", ephemeral=True)
async def setup(bot):
await bot.add_cog(Avatar(bot))```
!d discord.Member.avatar_url
No documentation found for the requested symbol.
!d discord.Member.avatar
property avatar```
Equivalent to [`User.avatar`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User.avatar)
this
property url```
Returns the underlying URL of the asset.
using
method you can get the url of avatar recieved from here

!d discord.Member.display_avatar is what u usually want if the user dosent have an avatar it returns url for the default one
property display_avatar```
Returns the member’s display avatar.
For regular members this is just their avatar, but if they have a guild specific avatar then that is returned instead.
New in version 2.0.
dumbass made the same mistake i did 😂
so i did
why is your UI like that
vencord plugin
wdym?
f
get banned off discord speedrun any%
nah.
i’d win.
Guys I heard that there is some issues with dank memer cuz discord had an update,does it put any effect on python bots?
dk
@app_commands.context_menu(name="Test", default_permissions=discord.Permissions.manage_messages)
@app_commands.guild_only()
async def context_menu_test(interaction: discord.Interaction, user: discord.Member):
await interaction.response.send_message(f'Test {user.mention}', ephemeral=True)
I have a question regarding default_permissions in a contxt menu, how can I set these? because here if I try to do this it doesn't work
!d discord.app_commands.context_menu
@discord.app_commands.context_menu(*, name=..., nsfw=False, auto_locale_strings=True, extras=...)```
Creates an application command context menu from a regular function.
This function must have a signature of [`Interaction`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction) as its first parameter and taking either a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member), [`User`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User), or [`Message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message), or a [`typing.Union`](https://docs.python.org/3/library/typing.html#typing.Union) of `Member` and `User` as its second parameter.
Examples...
I don't see the argument anywhere in the docs 
I figured it out sorry 😅 I just had to add a seperate decorator for it
@app_commands.default_permissions()
https://discordpy.readthedocs.io/en/stable/interactions/api.html?highlight=context menu#discord.app_commands.ContextMenu.default_permissions Read it from here, got a little confused
Ah, right
dank memer uses djs which is dpy but a js version (in simple)
whats the issue?
“server wide raid” according to this video: the video
On This Video:➥ On March 27th, 2020. A glitch in the code of the Discord Bot known as "Dankmemer" caused this server-wide raid. This raid was brought with th...

seems like a dank issue and not a discord issue
heh... dank...
how can we make discord bots
depends. how do you want to make them?
!pypi discord.py is a good library to use - almost everyone uses it
Hello, I would like to host a discord bot in python you know of good hosts I saw the o2switch offer what do you recommend to get started (I also use selenium with the server)
!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.
thanks
hey anyone knows why the suggestion only shows up when i type in a letter in the search bar ?
i allready tried removing if current.lower() in profit_symbol.lower(): but then the whole auto suggestion stops working
!code show the whole thing
!traceback and this if possible
Please provide the full traceback for your exception in order to help us identify your issue.
While the last line of the error message tells us what kind of error you got,
the full traceback will tell us which line, and other critical information to solve your problem.
Please avoid screenshots so we can copy and paste parts of the message.
A full traceback could look like:
Traceback (most recent call last):
File "my_file.py", line 5, in <module>
add_three("6")
File "my_file.py", line 2, in add_three
a = num + 3
~~~~^~~
TypeError: can only concatenate str (not "int") to str
If the traceback is long, use our pastebin.
@viscid hornet ```py
import discord
from discord.ext import commands
from discord import app_commands
color_saura = discord.Color.from_rgb(173, 216, 230)
class Say(commands.Cog):
def init(self, bot):
self.bot = bot
@app_commands.command(name="say", description="Di algo")
@commands.has_permissions(manage_messages=True)
async def say(self, interaction: discord.Interaction, *, content: str):
await interaction.response.send_message("Mensaje enviado.", ephemeral=True)
await interaction.channel.send(f"{content}")
@say.error
async def say_error(self, interaction: discord.Interaction, error):
if isinstance(error, commands.MissingPermissions):
await interaction.response.send_message(f"Necesitas el permiso `Gestionar mensajes` para ejecutar este comando.", ephemeral=True)
return
async def setup(bot):
await bot.add_cog(Say(bot))```
whats the issue?
I have an error and that is that if you do not have permissions it does not execute the @say_error
also you should always end your error handler with “else: raise error”
otherwise you’ll end up eating error messages and wondering why stuff wont work
cuz you’re not checking for it
I already have it
are you sure?
yeah
doesnt look like it
@bot.event
async def on_command_error(ctx, error):
if isinstance(error, commands.CommandNotFound):
embed = discord.Embed(title="Comando no encontrado", description=f" El comando `{ctx.invoked_with}` no se encuentra en mi codigo.", color=color_saura)
await ctx.send(embed=embed)
elif isinstance(error, commands.CommandError):
embed = discord.Embed(title="Error inesperado", description=f"Ha ocurrido un error ejecutando el comando. ```{error}```", color=color_saura)
await ctx.send(embed=embed)
else:
raise error```
@app_commands.autocomplete(item=profit_autocompletion)
async def profit(interaction: discord.Interaction,
item: str
):
with open(json_file_path, 'r') as f:
user_wallets = json.load(f)
user_id = str(interaction.user.id)
user_wallet = user_wallets[user_id]
tx = calculate_p(item,user_wallet)
embed=discord.Embed(title=tx["token_symbol"],color=6645140)
embed.add_field(name="profit/loss",value=f"${tx['profit_or_loss']} USD")
del user_cache[user_id]
await interaction.response.send_message(embed=embed)```
!paste put it in here cuz i cant read syntax on ios
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.

yes, thats on your global command error handler
your local handler takes more priority

the same way you’d visit friends who live closer to you more than those who live a city away or a country away
wait what is this in?
a cog? a main file?
import discord
from discord.ext import commands
from discord import app_commands
color_saura = discord.Color.from_rgb(173, 216, 230)
class Say(commands.Cog):
def __init__(self, bot):
self.bot = bot
@app_commands.command(name="say", description="Di algo")
@commands.has_permissions(manage_messages=True)
async def say(self, interaction: discord.Interaction, *, content: str):
await interaction.response.send_message("Mensaje enviado.", ephemeral=True)
await interaction.channel.send(f"{content}")
@say.error
async def say_error(self, interaction: discord.Interaction, error):
if isinstance(error, commands.MissingPermissions):
await interaction.response.send_message(f"Necesitas el permiso `Gestionar mensajes` para ejecutar este comando.", ephemeral=True)
else:
raise error
async def setup(bot):
await bot.add_cog(Say(bot))```
im seeing app commands and bot.tree.cmd in the same place
?
yes
ok, im test
also send full tb when smth goes wrong
tb is short for traceback
main im just testing rn
Still does not send the error message if the user does not have the necessary permissions
is there anything in terminal?
nop
Cog valido: syncup
Cog valido: help
Cog valido: ping
Cog valido: avatar
Cog valido: say
Conectado a Discord
_____
/ ___/____ ___ ___________ _
\__ \/ __ `/ / / / ___/ __ `/
___/ / /_/ / /_/ / / / /_/ /
/____/\__,_/\__,_/_/ \__,_/
Prefix: [?] Bot: [Pruebas#3847]```
damn it
you’re using ephemerals. are you sure nothing gets sent?
i feel like this could be solved with an app commands check
the command works, what doesn't work is the @say_event when the user who executes the /say does not have the manage messages permission
how come theres indents then?

!d discord.ext.commands.MissingPermissions
exception discord.ext.commands.MissingPermissions(missing_permissions, *args)```
Exception raised when the command invoker lacks permissions to run a command.
This inherits from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure)
!d discord.ext.commands.has_permissions
@discord.ext.commands.has_permissions(**perms)```
A [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check) that is added that checks if the member has all of the permissions necessary.
Note that this check operates on the current channel permissions, not the guild wide permissions.
The permissions passed in must be exactly like the properties shown under [`discord.Permissions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions).
This check raises a special exception, [`MissingPermissions`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.MissingPermissions) that is inherited from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure).
@commands.has_permissions(manage_messages=True)
yeah im tryna think
i say just use an app commands check
ok thx
!d discord.app_commands.check
@discord.app_commands.check(predicate)```
A decorator that adds a check to an application command.
These checks should be predicates that take in a single parameter taking a [`Interaction`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction). If the check returns a `False`-like value then during invocation a [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CheckFailure) exception is raised and sent to the appropriate error handlers.
These checks can be either a coroutine or not.
Examples
Creating a basic check to see if the command invoker is you...
@slim bloom read into these examples
@discord.app_commands.check(manage_messages=True)```
?
you need a separate function
???
wait lemme do some digging rq
@discord.app_commands.check(has_manage_messages)```
?
yes
and then has_manage_messages would be a function
if isinstance(error, commands.CheckFailure):``` ?
wrong check lmao
!discord.Guild.permissions
god i need sleep
class discord.Member```
Represents a Discord member to a [`Guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild).
This implements a lot of the functionality of [`User`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User).
x == y Checks if two members are equal. Note that this works with [`User`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User) instances too.
x != y Checks if two members are not equal. Note that this works with [`User`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User) instances too.
hash(x) Returns the member’s hash.
str(x) Returns the member’s handle (e.g. `name` or `name#discriminator`).
x == y
?
?
im new to discord bot. how is it monetizable? seems too many communities and too many people working on it. is it mostly just making cmds?
- you can monetise it with premium features
- yes bots are just commands — thats what makes them work
ok cool. yeah just wondering cause it seems like a lot of interest. im just sniffing for the opportunities. ok, carry on then
!d discord.Member.guild_permissions
property guild_permissions```
Returns the member’s guild permissions.
This only takes into consideration the guild permissions and not most of the implied permissions or any of the channel permission overwrites. For 100% accurate permission calculation, please use [`abc.GuildChannel.permissions_for()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.GuildChannel.permissions_for).
This does take into consideration guild ownership, the administrator implication, and whether the member is timed out.
Changed in version 2.0: Member timeouts are taken into consideration.
!d discord.Permissions.manage_messages
Returns True if a user can delete or pin messages in a text channel.
Note
Note that there are currently no ways to edit other people’s messages.
this is a Permissions object
and this is how you can check if they have manage messages perms
@viscid hornet now work ```py
import discord
from discord.ext import commands
from discord import app_commands
color_saura = discord.Color.from_rgb(173, 216, 230)
class Say(commands.Cog):
def init(self, bot):
self.bot = bot
@app_commands.command(name="say", description="Di algo")
async def say(self, interaction: discord.Interaction, *, content: str):
if interaction.user.guild_permissions.manage_messages:
await interaction.response.send_message("Mensaje enviado.", ephemeral=True)
await interaction.channel.send(content)
else:
await interaction.response.send_message("Necesitas el permiso `Gestionar mensajes` para ejecutar este comando.", ephemeral=True)
async def setup(bot):
await bot.add_cog(Say(bot))```
yeah that works
also you should check if its in a guild or not
dms are a thing and that will fuck up the command
property guild```
The guild the interaction was sent from.
it can either be a Guild or None
so if its None then tell the user they cant use the command there
Are all channel ids the max length of 19?
The channel ID.
it doesn’t say anything about it
L
try the dpy server - you’ll get better answers
@app_commands.command(name="say", description="Di algo")
async def say(self, interaction: discord.Interaction, *, content: str):
if interaction.guild is None:
await interaction.response.send_message("Este comando solo puede ser usado en un servidor.", ephemeral=True)
return
if interaction.user.guild_permissions.manage_messages:
await interaction.response.send_message("Mensaje enviado.", ephemeral=True)
await interaction.channel.send(content)
else:
await interaction.response.send_message("Necesitas el permiso `Gestionar mensajes` para ejecutar este comando.", ephemeral=True)```
good?
mf you asked here 😭
perfect 👍🏽
yeahhhhh but ion feel like finding the folder that has dpy server in it 😁
alr
called being lazy 
how come that one is in a folder and this one isnt
This one is

but this is the server i like more
the other server i hate more 😁
they are more of a TOXIC community lmao
they toxic but they got the answers 🤷🏽♂️

try:
channel_id_int = int(channel_id)
except ValueError:
embed = ErrorEmbed(
title="Error",
description="The provided channel ID is not a valid integer.",
)
await interaction.followup.send(embed=embed, ephemeral=True)
return
channel = interaction.guild.get_channel(channel_id_int)
if channel is None:
embed = ErrorEmbed(
title="Error",
description="The provided channel ID does not correspond to a channel in this server.",
)
await interaction.followup.send(embed=embed, ephemeral=True)
return```
this will do 😁
?
are you guys working from one repository? im still green. are your projects pretty tight net or do you have some open source ones where people can slowly jump in and contribute until their added value gets considerable?
varies from person to person 🤷🏽♂️
this doesnt sound very discord bot like 
to #python-discussion you go
aways, sell cheap thi
?
@viscid hornet i need help
from only owner can use slash command: ```py
import discord
from discord.ext import commands
from discord import app_commands
import os
color_saura = discord.Color.from_rgb(173, 216, 230)
class Reload(commands.Cog):
def init(self, bot):
self.bot = bot
@app_commands.command(name="reload", description="Recarga todos los cogs del bot")
@app_commands.is_owner()
async def reload(self, interaction: discord.Interaction):
for filename in os.listdir("src/cogs"):
if filename.endswith(".py"):
await self.bot.unload_extension(f"src.cogs.{filename[:-3]}")
for filename in os.listdir("src/cogs"):
if filename.endswith(".py"):
await self.bot.load_extension(f"src.cogs.{filename[:-3]}")
embed = discord.Embed(title="Cogs recargados", description="Todos los cogs han sido recargados.", color=color_saura)
await interaction.response.send_message(embed=embed)
@reload.error
async def reload_error(self, interaction: discord.Interaction, error):
if isinstance(error, commands.NotOwner):
await interaction.response.send_message("No tienes permiso para utilizar este comando.", ephemeral=True)
async def setup(bot):
await bot.add_cog(Reload(bot))```
what?
whatchu tryna do
a command called reload that reloads all cogs
ait
Slash commands are public and published
you forgot to raise the error in the handler
You shouldn't be using them for something you specifically want to keep to yourself. That entirely defeats the purpose of the system
and what do I do?
wdym
Don't use slash commands for private bot functionality, it's pretty simple
prefix?
like if ur tryna make owner only command
Or whatever else you wanna do, just not something that's broadcast to all of your users
but I wanted my bot to be 100% just slash
I mean you can make a guild slash command for a private guild only you are in but that's a ton of hassle for no gain and only risk that you accidentally mess up
I mean that's like saying you want a bot with only vowels
lmfaooo
Why limit yourself on the tools that do the job you want better
can you not just use an “only for me” app commands check?
thatsa pretty unnecessary handicap
That doesn't prevent what I was saying about private functionality being broadcast to all of your users for no point
ohh thats what you meant. i see 👍🏽
which one
is the discord bot subscription model tricky to get sign ups with a beginner project? do you need a community /social media to funnel from? i'm trying to figure out my next project
Yo u got them slash commands by any chance or nah? Need help :[
@viscid hornet
How do I make my slash command only able to be executed by the owner of the bot?
check
if ctx.author.id != 128391729837129471294 # Owner id
return await ctx.response.send_message("You are not allowed to do this command!", ephemeral=True)
@slim bloom
something like this
yeah
import discord
from discord.ext import commands
from discord import app_commands
color_saura = discord.Color.from_rgb(173, 216, 230)
class Syncup(commands.Cog):
def __init__(self, bot):
self.bot = bot
async def is_owner(self, interaction: discord.Interaction):
return interaction.user.id == self.bot.owner_id
@app_commands.command(name="syncup", description="Sincroniza los comandos slash")
async def syncup(self, interaction: discord.Interaction):
if not await self.is_owner(interaction):
await interaction.response.send_message("No tienes permiso para utilizar este comando.", ephemeral=True)
return
await self.bot.tree.sync()
embed = discord.Embed(title="Slash sincronizados", description="Todos los comandos slash han sido sincronizados.", color=color_saura)
await interaction.response.send_message(embed=embed, ephemeral=True)
async def setup(bot):
await bot.add_cog(Syncup(bot))```

yo solstice
how would i implement a splitting logic?
Im having problems at letting the user hit and hold on each hand
as of right now i have three lists.
- First hand
- Second hand (if split)
- Hands (contains all hands)
I thought of iterating through the hands list and doing something in the logic of the hit and hold button
but idk what

import discord
from discord.ext import commands
from discord import app_commands
import os
color_saura = discord.Color.from_rgb(173, 216, 230)
class Syncup(commands.Cog):
def __init__(self, bot):
self.bot = bot
async def is_owner(self, interaction: discord.Interaction):
return interaction.user.id == self.bot.owner_id
@app_commands.command(name="syncup", description="Sincroniza los comandos slash")
async def syncup(self, interaction: discord.Interaction):
if interaction.user.id != int(os.getenv("CREATOR_ID")):
await interaction.response.send_message("No tienes permiso para utilizar este comando.", ephemeral=True)
return
await self.bot.tree.sync()
embed = discord.Embed(title="Slash sincronizados", description="Todos los comandos slash han sido sincronizados.", color=color_saura)
await interaction.response.send_message(embed=embed, ephemeral=True)
async def setup(bot):
await bot.add_cog(Syncup(bot))```
Users are really going to love seeing a command that they're not allowed to run put into their faces for some reason
very fun

why are slash commands not hidden tho
if you do not have permissions to run it
Because discord doesn't know about local checks
And slash commands can always be run by server managers. Because you publish them. The entire point is to make people see them and use them
alright
what is that 😭🙏🏽
anyone have a google image bot working currently without any rate limits..? Or like barely any rate limits..?
just get an image with a defer at the start and some aiohttp magic, no?
I am talking about like
---img drugs
drugs being the query.
Then it grabs x amount of images from the query you gave.
But from google
I have something like this.
But with my current way, I can only do 100 requests per day. So I was wondering if anyone had another way that can go past that limit? or that has no limits.
my commands arent working at all.
import json
import random
import discord
import os
import requests
from discord.ext import commands
from discord.ext.commands import has_permissions
import urllib
from web_server import keep_alive
intents = discord.Intents.default()
intents.messages = True
intents.members = True
client = commands.Bot(command_prefix="!",intents=intents)
@client.event
async def on_ready():
print("Bot is ready")
@client.command()
async def hello(ctx):
print("command executed")
await ctx.channel.send("Hello!")
keep_alive()
client.run("[INSERT TOKEN HERE]")
either im using some outdated method because i have not used dpy in a while
enable message content intents, intents.message_content = True
is it just me or assigning client to a commands.Bot instance has become norm
can someone look up to my code it deletes the messages but fail to send a message saying it deleted
async def clear(interaction: discord.Interaction, amount: int):
try:
if interaction.user.guild_permissions.manage_messages :
deleted = await interaction.channel.purge(limit=amount)
await interaction.response.send_message(f"{len(deleted)} mesaj silindi.")
except Exception as r :
await interaction.response.send_message(f"hata:{r}")```
you will need to defer this interaction first
it's a common thing among beginners
and then send an ephemeral followup
cuz i think if epehemeral is false the bot will delete the followup too
Yes it will.
It's funny because bot is better. But they try to use client lol
"better"
You can call the variable anything you want
It is technically a client that interacts with the api
It's common even i use it
Doesn't matter what you call it, sometimes i just name it Shoya instead of bot or client
it's not better, you can use Client for more low level things, eg. maybe you are not interested in commands and only want events
also using Client you can implement your own prefix command logic
Bot builds off of Client so technically, you can use your own prefix logic in Bot as well 🤷🏽♂️
Axo woke
i’ve seen prefix logic for Bot instances before
still in bed 😭

it's better to define it on a Client object because you are sure that you'll not miss anything out
Like internal methods or other methods that relies on default implementations
there might be some stuff online — take a look at it

Hi, is there any way i can clone a discord bot using some python code, I made a new bot on my server using discord.py, I want to make many instances of the same bot that execute the same code ( about 250 bots so i can't do it manually )
Any help would be appreciated
how about using the same bot in different servers?
are you trying to do sharding
whats that
whats even that lol

then you dont need it
my goal is to make many bots join same server not same bot jioning in different servers
sounds like a bot farm
Tokens (fake members)
!rule tos
5. Do not provide or request help on projects that may violate terms of service, or that may be deemed inappropriate, malicious, or illegal.
He want online count i guess
whats your use case for this?
we’ll find out 🤷🏽♂️
New bot and 250 instances don't make much sense together 
I want to make a roleplaying bots, and everyone rely on others
oh thats what that logging line is. the “logging into shard id …”
yes
Still doesn't make sense
she*
can you expand?
That's what you want to focus on
So you just want every member to have their own bot instance? 
shes tryna remake irobot 😭
you know u can make the bot talk using ai right?
so basically i want to make 250 bots that with same code talk to each other
that sounds like schizo activity
reason for 250 bots is bc limit of roles is 250
😭😭 what is she upto
make em talk to each other on your PC
“the voices have manifested into discord bots”
Now I doubt if she meant bot or ||User IDs||
can u be much more respectful please
|| someone struck a nerve ||
i said 2 replies im not even being rude
I see no reason to have multiple bot instances when it doesnt comes to sharding, sounds like a weird idea
what's even sharding?
eh she's not trying to shard she's just trying to make different bot join the same server with the same code, its possible but it's just against tos
Dividing bot into shards for easy management of multiple servers
Biology?
still don't understand how this is related to my idea
No one ever taught me this
yeah thx
Hello guys, how can i check if a user is a webhook?
its possible but its against tos
just make them talk on your PC
She want bots in same server shading works completely opposite
thats actually a good question. lemme go digging through docs rq
Use case?
what specificly is against the ToS, coz i can do it manually but it takes so much time, so what reason that make it forbidden using some automated procedure
anti nuke
some nukes uses webhooks
so i need to check if the user nuking is a webhook
and delete the webhook
would Member.bot work? or are they different
Different
bot auto joins a guild sounds like a bot farm
potential use for server raiding
Axo seems experienced
i’d say im in the middle of things and i do my best to help yk 🤷🏽♂️
is bot farm and rading server relatively the same? coz idk what bot farm means
!d discord.AuditLogAction.webhook_create
A webhook was created.
When this is the action, the type of target is the Object with the webhook ID.
Possible attributes for AuditLogDiff...
i don't think raiding a server needs that many bots, two would be enough 💀
@formal basin
i dont want when it is created
i want when the user is a webhook
using if statment
this would only work with the server it was made in
User cannot be a webhook unless he creates it
can webhooks even join servers?
no
I guess you have to create specifically for server
but ive seen a webhook nuke a server
no, you’d need quite a lot if you were to raid a server. theres a reason battles are fought with thousands of men and not tens of men
2 different things, people used to make bot joins guild just to get the developer badge by joining 75 guilds making server bot farm exists, raiding is just targeting a specific server
What does a webhook do?
Webhook can only send a message
its created specifically for the server though?
might I ask what's a webhook, it sound similar to discord application but idk what's difference
!d discord.Webhook
class discord.Webhook```
Represents an asynchronous Discord webhook.
Webhooks are a form to send messages to channels in Discord without a bot user or authentication.
There are two main ways to use Webhooks. The first is through the ones received by the library such as [`Guild.webhooks()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild.webhooks), [`TextChannel.webhooks()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.TextChannel.webhooks), [`VoiceChannel.webhooks()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.VoiceChannel.webhooks) and [`ForumChannel.webhooks()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.ForumChannel.webhooks). The ones received by the library will automatically be bound using the library’s internal HTTP session.
The second form involves creating a webhook object manually using the [`from_url()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Webhook.from_url) or [`partial()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Webhook.partial) classmethods.
For example, creating a webhook from a URL and using [aiohttp](https://docs.aiohttp.org/en/stable/index.html):
no
its like a temporary bot account
first
a bot gets invited to the server
then gets kicked
Bot creates a webhook -> starts spamming
then a webhook just nukes the server
Don't ask where i got the experience 💀
spamming channels aswell
webhooks can only be used for sending, editing and deleting messages
thx
Yeah that's how it works dude
How else would you spam
dont go off and create 250 webhooks to fulfil a schizo fantasy. just run them on your own PC
thx
it cant though
You might want to see my GitHub for how it works 🤣
now that you mention it i might actually do it
Webhook cannot create channel
🤦🏽♂️
Bot does that
🤨
the bot got kicked though
but then created a webhook
then it just nuked the whole thing
run the code to output in your terminal or a logging file or some shit — dont bother with discord cuz you’ll eventually get ratelimited and everything will fall apart
webhooks quite literally cannot do anything outside of a normal user
alright
terminal is so boring man
and so are ratelimits
It can just send a message or embed apart from that it is useless @formal basin
what's ratelimits?
🤦🏽♂️
😭
think of it like lag
"Assurance" that you wont make multiple requests so the servers wont crash
why everyone laughing, i'm here to learn
discord will purposefully lag your requests if they’re in too quick succession
oh ok
Ray is much better explainer than us
Imagine having a gf and no matter how many messages you send her, she leaves you on delivered
That's not what rate limits do lol
That's little personal
jokes on you i use c.ai
Im jus trynna help
solstice feels like a mum trying to calm down her 6 toddlers who all had sugary drinks before bed

Discord sends headers on replies saying how many times it wants to allow you to do things, and if you do it more than that they start failing the requests
I wonder if we're really 6 here?
Solstices just too op
Exactly
🤦🏽♂️
That's what i was trynna explain
and the anti nuke was working


What does your antinuke contains
but the bot made 100 channels in 1 second
Seems dumb to me
so it looked like the anti nuke didnt work
That's normal 💀 ||slower than mine||
“please dont do it- ah fuck off mate you said you wouldnt. you said you wouldnt. ah man. damn it”
"Antinuke" as how most kids write them are just a band aid for people not understanding how permissions work. Just secure your damn servers
^ don't give sensitive permissions to random bots
but whys everyone ruining my server when i give the member role admin perms 😢
Bots grow because of those dumb kids 🤣
Recently one of my friend's bot crossed 100k servers it has only antinuke
find better admins
fr
You'd find delete server button more useful at this point
well everytime time a channel is created it is stored in list. Then it checks if 5 channels are stored under 7 seconds
could you clone a discord server?
5 channels/20seconds is crazy
Copy template?
besides messages other people have sent, theoretically you could just copy it
i meant 5/7
no like clone a discord server like this
not 20
|| i think at this point its just a discord template but with extra steps ||
Like what?
wdym
That sounds way too slow process
server template
anti nuke bots are quite useless just get trustable people as moderators and admins
If you're too dumb to not give random bots admin, why would you be smart enough to not give the random bot a higher role than your antinuke so it can just kick it
should i do 2 channels/1 second
I've seen servers where bots have higher roles than admins
cause they're moderation bots 😮
That's normal nowadays
this one
moderators after accidentally banning themselves 🤦🏽♂️
And what would you do with it
copy it?
anyways, what's recent with discord bots? Anything net in the API?
Just do it
actually happened to me once, I was messing around
theres user apps now
await create_guild(name, icon=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Creates a [`Guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild) using the template.
Bot accounts in more than 10 guilds are not allowed to create guilds.
Changed in version 2.0: The `region` parameter has been removed.
Changed in version 2.0: This function will now raise [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) instead of `InvalidArgument`.
the creator of that bot didn't even add a check to make sure the person they're kicking is a moderator or SAME PERSON
I remember when i was new to dpy someone came to me and said "i used ban command on myself and it worked i banned myself using bot"
why did they sound proud 😭🙏🏽
oh you mean user context menus?
After that i had to add if member == ctx.author
user apps
They found mistake in my bot 🤣
ah that rolled out with slash cmds iirc
User apps are different it's like direct action
I remember my first attempt to help someone with discord.py
i see
lucky that marvin didn't obliterate me 
🙈 time to start working on my API wrapper again
i remember this channel as asking for help as dumb begginner, now I'm able to help others
i remember getting help from solstice in 2020/21 when i was an absolute beginner and i could feel her trying not to destroy her monitor or hunt me down and execute me
real 😔
now im able to help others
as a dumb beginner
in the shower rn

dpy help grind dont stop
🤨
you dont help people while in the shower?
damn you suck at helping
real helpers know theres no days off 👍🏽
@slate swan can you confirm

Still better than you
And quicker
😢

🗣👌 stop speaking
You're not helping here just spamming your inner voice
There's no one who need help rn

the voices
fair enough
Inner voice

Why are you sad
it was relatable 

exams done?
mine just got over
bro i want to help
pls make the cache fully, and i mean fully, customizable / manageable
i have already given up on sarth bro gonna work for 2 days then go for a 2 year hiatus 💀 his updates are slower than some unknown manga series author
@viscid hornet ```py
import discord
from discord.ext import commands
from discord import app_commands
import os, mysql.connector, time
color_saura = discord.Color.from_rgb(173, 216, 230)
class Ping(commands.Cog):
def init(self, bot):
self.bot = bot
self.database = database = mysql.connector.connect(
host=os.getenv("MYSQL_HOST"),
port=os.getenv("MYSQL_PORT"),
user=os.getenv("MYSQL_USER"),
password=os.getenv("MYSQL_PASSWORD"),
database=os.getenv("MYSQL_DATABASE")
)
@app_commands.command(name="ping", description="Muestra mi latencia")
async def ping(self, interaction: discord.Interaction) -> None:
bot_latency = round(self.bot.latency * 1000)
cursor = self.database.cursor()
start_time = time.time()
cursor.execute("SELECT 1")
result = cursor.fetchone()
cursor.close()
database_latency = round((time.time() - start_time) * 1000, 2)
embed = discord.Embed(title="Pong", color=color_saura)
embed.add_field(name="Bot", value=f"{bot_latency}ms", inline=True)
embed.add_field(name="Database", value=f"{bot_latency}ms", inline=True)
await interaction.response.send_message(embed=embed)
async def setup(bot):
await bot.add_cog(Ping(bot))```
!d discord.Message.activity
The activity associated with this message. Sent with Rich-Presence related messages that for example, request joining, spectating, or listening to or with another member.
It is a dictionary with the following optional keys:
• type: An integer denoting the type of message activity being requested.
• party_id: The party ID associated with the party.
What could I change or improve?
yeahhh next IA starts from 29th
ia?
sure, I'll be rewriting stuff from scratch
29th this month?
but I need more people
constant hoax in my life LMAO
Is it considered as "application"?
internal assessments, yeah 29th this month
i see noice noice
mysql is blocking use aiomysql
see above that, the url is pointing to activity not application
Where can I find the list for type?
!blocking | what asher said but this gives more info
Imagine that you're coding a Discord bot and every time somebody uses a command, you need to get some information from a database. But there's a catch: the database servers are acting up today and take a whole 10 seconds to respond. If you do not use asynchronous methods, your whole bot will stop running until it gets a response from the database. How do you fix this? Asynchronous programming.
What is asynchronous programming?
An asynchronous program utilises the async and await keywords. An asynchronous program pauses what it's doing and does something else whilst it waits for some third-party service to complete whatever it's supposed to do. Any code within an async context manager or function marked with the await keyword indicates to Python, that whilst this operation is being completed, it can do something else. For example:
import discord
# Bunch of bot code
async def ping(ctx):
await ctx.send("Pong!")
What does the term "blocking" mean?
A blocking operation is wherever you do something without awaiting it. This tells Python that this step must be completed before it can do anything else. Common examples of blocking operations, as simple as they may seem, include: outputting text, adding two numbers and appending an item onto a list. Most common Python libraries have an asynchronous version available to use in asynchronous contexts.
async libraries
- The standard async library -
asyncio - Asynchronous web requests -
aiohttp - Talking to PostgreSQL asynchronously -
asyncpg - MongoDB interactions asynchronously -
motor - Check out this list for even more!
type: An integer denoting the type of message activity being requested.
!d discord.ActivityType
class discord.ActivityType```
Specifies the type of [`Activity`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Activity). This is used to check how to interpret the activity itself.
This is not what I was asking for
I want to detect when members are sending game invites in channels
^^ This kind of stuff
message.activity["type"] will return the activity type integer of ActivityType.listening in this case
Bruh what the bot doesn't embed code anymore?
class ActivityType(enum.IntEnum):
"""Type of activity."""
GAME = 0
"""The user is playing a game."""
STREAMING = 1
"""Activity where user is streaming."""
LISTENING = 2
"""Listening activity."""
WATCHING = 3
"""Watching activity."""
CUSTOM = 4
"""This activity is a custom status."""
COMPETING = 5
"""Compoeting activity."""
it was literally the same as what I sent rn
@client.listen()
async def on_message(message):
type = message.activity["message.content"]
print(type)
no
No this wont' work 
type instead of message.content in the square brackets
message.activity.get("type")
this will also raise an error if there's no activity
its optional so u would want to check if its present
use .get() man
once thats done throw it in some match case or if else stuff to perform whatever u want
Asher do you wanna leetcode with me
sure from tmrw tho ig
sure I'm following strivers's A-Z sheet
why leetcode tho suddenly?
I need someone who can keep pushing me for it
no idea what that is 💀
im doing since 10days probably
and ofc its me pushing u since eternity
damn fancy
it's so nice you should check it out
https://takeuforward.org/strivers-a2z-dsa-course/strivers-a2z-dsa-course-sheet-2
type = message.activity.get("type") AttributeError: 'NoneType' object has no attribute 'get'
cool
( it's free, not a promo)
oh lmao message.activity is None as well
add another check
you just need to check for message.activity, if that exists type will exist as well
probably a ternary statement
how far did u get?
Medium arrays
Something simple as
if message.activity:
print("Yes")
else:
print("No")
sure
Works
activity = "yes" if message.activity else "No"
``` here's something cleaner
What is 4 and 5?
( for your case )
aight cya have plans for dinner tonight
What is it for dinner?
outside with friends lol college exams got over
This includes activities that appear on your profile
.CUSTOM is the custom status you sent on discord
. COMPETING is some other activity that discord added for games
have fun
My goal is to remove messages for "game invites" only. I still want to allow spotify invites etc.
- check if message.activity exists
- If it does check the type of the activity
- If it's 0, delete the message
wait you want everything other than games
Yes
only gaming and Spotify activities can be embedded from I've seen
It says type 1
At least for League of Legends game invites
Spotify is type 3
Are you sure this list is accurate?
it is
Apparently enums for message activities are different
use this instead
1 2 and 5 are for games
TypeError: 'dict' object is not callable
if message.activity.get("type") and message.activity(1, 2, 5):
await message.delete()
Hmh I'm doing something wrong
message.activity(1,2,5) is wrong
how to add icon to a role using discord.py library?
x = {"type": 2}
print(x["type"] in (1,2,5))
``` you can use the `in` statement
!d discord.Role.edit
use the display_icon kwarg
await edit(*, name=..., permissions=..., colour=..., color=..., hoist=..., display_icon=..., mentionable=..., position=..., reason=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Edits the role.
You must have [`manage_roles`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_roles) to do this.
All fields are optional.
Changed in version 1.4: Can now pass `int` to `colour` keyword-only parameter.
Changed in version 2.0: Edits are no longer in-place, the newly edited role is returned instead...
I know, but display_icon takes bytes like object, and i have no idea how to deal with objects like this
i already have img installed on my directory
read the image with open to get the bytes of that file, as in ```py
with open('file/path.png', 'rb') as r:
byte = r.read()
Thank you
'rb' is a mode to read in binary
thank you, hopefully that will do
how can I set through the bot the permissions on a slash command?
so that they also apply to the example above (they can also be seen in Server Settings/Integrations)
!d discord.app_commands.default_permissions
@discord.app_commands.default_permissions(**perms)```
A decorator that sets the default permissions needed to execute this command.
When this decorator is used, by default users must have these permissions to execute the command. However, an administrator can change the permissions needed to execute this command using the official client. Therefore, this only serves as a hint.
Setting an empty permissions field, including via calling this with no arguments, will disallow anyone except server administrators from using the command in a guild.
This is sent to Discord server side, and is not a [`check()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.check). Therefore, error handlers are not called.
Due to a Discord limitation, this decorator does nothing in subcommands and is ignored.
should be this
thank you sir!
also just a question if you already tried to store stickers as json file
stickers.emoji display this \ud83d\ude31
will this worrk if i later decide to create sticker with that argument as parameter to emoji?
yes it should be, from the look of the docs it accepts emoji
that's just a unicode version of that emoji so it shouldn't be a problem
thx
i can use has_any_role on this?
Anyone a Ohio skibidi fanum tax Ohio rizzler
!ot
Please read our off-topic etiquette before participating in conversations.
also, should i work with icon or display_icon?
name confuses me a bit
whats that with?
role icon not emoji
!d discord.Role.icon
property icon```
Returns the role’s icon asset, if available.
Note
If this is `None`, the role might instead have unicode emoji as its icon if [`unicode_emoji`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role.unicode_emoji) is not `None`.
If you want the icon that a role has displayed, consider using [`display_icon`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role.display_icon).
New in version 2.0.
!d discord.Role.display_icon
property display_icon```
Returns the role’s display icon, if available.
New in version 2.0.
doesnt really work the same as default_permissions, but app_commands.checks.has_any_role, it's a check so its server side rather than client side
im guessing icon is more general and includes unicode emojis (ie. this is valid: ❤️, and so is this: 😄) but display_icon will give you the custom role icon (if available)
so icon can be:
- a custom emoji
- a default emoji
None
but display_icon can only be:
- a custom emoji
None
if message.activity and message.activity.get("type") in (1,2,5) to ignore the error messages right?
any idea how i can do that?
im not sure what is that since its not in english
Understood
that just lets you add overrides to the command
so for example, say a command has a cooldown of 30s: mods and admins and whatnot could be able to use it instantly
that can't be set through the bot, only perms
ok!
so its only for the server admins
yea
!d discord.Guild.icon
property icon```
Returns the guild’s icon asset, if available.

Can’t connect modules
This should raise an error if you're running dpy 2.x
So I should update
If you're running on lower than 2 it won't work at all lol
I guess no because I installed since 3 days
yes
any way to make the slash command/commands visible only for some members (like mods? )
The integrations UI on the server
What library are you installing? Not python
must do it manually ? can't define it at code?
Lemme check
Your code doesn't know all of the roles in all of the servers a bot could be in
its only in 1
Well the api doesn't change to accommodate that
So it's not possible and it has to be done manually?
Plus they don't want you to have to redeploy code every time server managers decide they want to permission things differently. It's very easy on the UI
All you can do is limit on default permissions, which are global. Not roles
What thing I update?
I forgot
^
Version of discord.py?
If that's the library you're using then yeah
3.7
Then yeah the code you have should throw an error if you try to run it
So
How I update

that's the most recent stable version
The code you have, if run against dpy 2.x, will error. Which means if you're running it and not getting an error, you aren't running it against dpy 2.x
are there any free python courses anyone would recommend for someone starting from no experience
This typically means either a) you are running against a different python installation than what you're looking at with pip or b) you have other libraries installed that are interfering
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
thank you
#bot-commands
im tryna replicate their issue
but yeah i'll go there
since you're using discord.py, see the following:
https://discordpy.readthedocs.io/en/stable/migrating.html#migrating-2-0-commands-extension-cog-async
They're not getting the malloc warning so it's one of these most likely
weird thing however, that's the 2.x logging format
and that error would show up higher up in the log trace, we can only see text after a print that occurs within on_ready
can someone spoonfeed me? cos the spaces for my mute commands and the durations isnt working https://sourceb.in/ZHf7yFiAwt
please and thank you
no we wont spoonfeed you
as for your mute issue, define "spaces" for me
also dont use py except Exception as e: print(e) # or some equivalent
it doesn't output traceback
yes we will
no we wont
if you want to send a message with an error, use the traceback module (its a stdlib module): py import traceback
and then use: py traceback.format_exc()
or .format_exception(e) but idk the difference 🤷
!d discord.Member.timeout - use this instead of roles. i helped a guy earlier who spent 4 hours trying to get role perms working and using this, his issue got solved in 20 minutes
await timeout(until, /, *, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Applies a time out to a member until the specified date time or for the given [`datetime.timedelta`](https://docs.python.org/3/library/datetime.html#datetime.timedelta).
You must have [`moderate_members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.moderate_members) to do this.
This raises the same exceptions as [`edit()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member.edit).
relax gang i already figured it out when someone told me why its not working
oh thats quite nice why thank u
!d discord.ext.commands.Context.command
The command that is being invoked currently.
oi
so you think timeout is better than roles?
yeah obviously
thats like asking if leaving your bread out in the sun for the day is better than a toaster
theres no comparison
well if you wanted to have a place where they can talk, like a "jail" of some sorts, or some other edge case then yes, roles would be used
but im assuming you just want to make a mute command and call it a day
bro what is that analogy 💀
im hungry ok leave me alone 💀
i was thinking about getting bread while writing that
and if you're just making a thin wrapper over timeout, there already exists a timeout command natively that builds in proper auditing and access controls. Making one yourself that doesn't add anything is a degradation of functionality
wait is there actually a slash command for timeouts?
That won't work if you want to mute people in specific channels only
holy fuck there is
yes - if you read further i mentioned edge cases for what i considered applicable for a general use case
ie. if you wanted to have specifics or additional operations on timeouts, you would have to use roles and role permissions
personally i like to blow on my bread with a hair drier

but you do you man
how do i run my discord.py via a .bat file? like i see people that can contol their bot from a .bat
for example:
You can do the same with bot. But bot allows more things than client. From personal experience.
Its just using commands that are available in cmd.exe
the most common/basic would be
@echo off
python bot.py
and pause
right?
yeah
how do i shut down the bot / make it go offline now?
i closed the bat and its still online..
Is there any particular reason you want this extra level of indirection?
@viscid hornet code is good? ```py
@bot.event
async def on_shard_ready(shard_id):
print(Fore.LIGHTGREEN_EX + f"Shard {shard_id} is now ready.")
@bot.event
async def on_shard_connected(shard_id):
print(Fore.LIGHTGREEN_EX + f"Shard {shard_id} has been connected.")
@bot.event
async def on_shard_resumed(shard_id):
print(Fore.LIGHTYELLOW_EX + f"Shard {shard_id} has been resumed.")
@bot.event
async def on_shard_disconnect(shard_id):
print(Fore.LIGHTRED_EX + f"Shard {shard_id} has been disconnected.")
await bot.reconnect()```
me?
uhh
idk
no reason

for fun
Right
how can i make the question pop up after the bot has been logged into?
input()
also why are you censoring the time 😭
why not
🤷
i dont want random people to know my time
what does censoring the time do 💀
nothing
so why do it then 💀
expose exact location via time zone

onb
timezones are like a slice of the planet - there's nothing sensitive about that 😭
yeah that's the joke
oh wait you meant after
for after, just print() stuff
yes
for a school project👍
If your school wants you to add random layers of indirection for no reason, that's a shitty school
i lied🤷
why is the school assigning dpy projects 💀

is there a way to secure you account from rate limited?
ratelimits exist for a reason - the whole point of enforcing them is for you not to be able to circumvent them
they're a limit on the rate of your action
im so confused because the bot will get logged into, only after i answered 
yes because input() takes input from the console
"im gay"
ignore that
XD
i didn't say how can i disallow them , maybe my eng is bad to comprehend, but i mean if there is some security advices so i make sure not to exceed rate limit
so i don't rich the limit on the rate of my actions
ohh thats what you meant. for that, just do the process
discord doesnt specifically outline ratelimits
so the only way to tell is to do the processes yourself and see what gets hit by ratelimits and what doesnt
think of it like pausing the process and waiting for input then continuing the process
i have a feeling you dont know python basics
i might try to time.sleep(1) but idk if my bot can run on every s
maam idk whats going on, i removed the input and the print doesnt appear after the bot has been logged into
time.sleep(3) or asyncio.sleep(3)
use asyncio.sleep because time.sleep is blocking
oh wait, isnt' the purpose of async is to execute code even if some function or procedure is sleeping?
oh thx
yes 👍
because im guessing you did this: py print("hello") bot.run(token)
i have a feeling you dont know python basics and dpy explicitly advises you learn that before learning how to use their library.
!resources ⬇️
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
is asyncio built-in or i have to instsall it?
i have other scripts before that
built-in so just import it
!paste | show the whole code for your main file
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.
good
no
!paste is the command and because it doesnt take any arguments after that, you can put whatever you want
since its not counted in the command
!paste se
!paste py from asyncio import asyncio
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.
5
yh
send it here
no
why?
what was the point of pasting it anyway if you weren't gonna send it?
ill try to fix it myself
|| (should've been the first thing you tried) ||
i did try, but aii
registers a chatgpt acc
goodluck
!rule ai
there's a reason this is a rule
im js askin it how to fix my problem
chat gpt doesnt have any updated info about dpy
and its because gpt is terrible at fixing code
no one here can help
you'd have better luck asking the stars for table salt
im right here yk, and so is smile guy and so is aluminium
u didnt send us the code, u didnt send us the exception 😭
yeah at the end
its like trying to diagnose cancer but you cant see the person and u cant touch them
!res | yeah bro you got no idea how python works if you're wondering why having a print before the run statement means that it gets printed before the dpy logging
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
when making function in discord.py
correct me if i'm wrong
async def my_func(guild):
pass
@client.event
async def on_ready():
guild = discord.utils.get(client.guilds, name="my server")
await my_func(guild)
👍
thx
same for any function in any scenario
ok
so basically rule of thumb, if my_func have any async func, the parent has to be async too
I'm down to contribute if you need it
tell me then
i js started
deep
yes
the link in the embed should help you
read this list:
- get eggs
- get milk
tell me which of these items is first and which of these items is second
"no"
write it in a formula
this was already said, ofc that you can do it too but implementing it on the Client is better (imo) because you implement the system from scratch in a clean class that doesn't have any logic involved with that, removing some risks
plot twist: it's a set
do u think im blind
limit = k(action/time) BOOM
IndexError: set does not support item assignment
yes
y?
Well, it depends on what the function is doing. If your "async function" is only calling sync methods/functions within it, it loses its async property and acts as a sync function in the end
why
the first one is first and the second one is second
yeah i was only worried if i make function sync but its calling async
because you wondered why this: ```py
print(1)
print(2)
produces this ```py
1
2```
and not this: ```py
2
1```
congratulations: you've figured out order
that should solve your issue 👍
u want me to put the print down there?
Only if you need to await something, make the function async otherwise there's no point in it
bro wth
try it and see 🤷
true
is it safe in python to make a function argument guild and work on it just like when i do in on_ready()? coz i'm afraid if i execute the code and the object is unkown to python
yeah that works fine
it only wouldnt know about it if you tried to reference guild when guild didnt exist
i see
so if you did: py async def my_func(something): print(guild.id)
this would not work because you're referencing guild which doesnt exist in the function
Depends on what you're doing in the function and what's being passed into it, the bots cache isn't fully loaded during the on_ready so if you try get any guild object or smth it'll mostly be None
!e ```py
def func(a):
print(b + 1)
func(13)```
@viscid hornet :x: Your 3.12 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "/home/main.py", line 4, in <module>
003 | func(13)
004 | File "/home/main.py", line 2, in func
005 | print(b + 1)
006 | ^
007 | NameError: name 'b' is not defined
however if i change the parameter to b

