#discord-bots
1 messages Β· Page 1146 of 1
What do you mean by "wrong moments"?
I have json file:
{"996181533356462200":{"t":15},"996178824540737598":{"t":13}}
I want to change the values of each message to 1, so that I can delete messages later when the value is 0, but I don't know how to change the values by picking up the ID of messages. (python)
when i type !trustlist 491582985326559253 , the bot will reply me with the 2nd and 3rd reply
at the same time
So "this user doesn't have ban" and "user is now whitelisted" at the same time?
yes
Hmmm
That's odd because the else block is supposed to run if there is no error in the try block
there is no error
can somebody help me to fix?
!indents
Indentation
Indentation is leading whitespace (spaces and tabs) at the beginning of a line of code. In the case of Python, they are used to determine the grouping of statements.
Spaces should be preferred over tabs. To be clear, this is in reference to the character itself, not the keys on a keyboard. Your editor/IDE should be configured to insert spaces when the TAB key is pressed. The amount of spaces should be a multiple of 4, except optionally in the case of continuation lines.
Example
def foo():
bar = 'baz' # indented one level
if bar == 'baz':
print('ham') # indented two levels
return bar # indented one level
The first line is not indented. The next two lines are indented to be inside of the function definition. They will only run when the function is called. The fourth line is indented to be inside the if statement, and will only run if the if statement evaluates to True. The fifth and last line is like the 2nd and 3rd and will always run when the function is called. It effectively closes the if statement above as no more lines can be inside the if statement below that line.
Indentation is used after:
1. Compound statements (eg. if, while, for, try, with, def, class, and their counterparts)
2. Continuation lines
More Info
1. Indentation style guide
2. Tabs or Spaces?
3. Official docs on indentation
I tried this but gave an error
allow_channels = [47283746372828,294746292934]
with open("json.json","r") as f:
j = json.load(f)
for idq in j:
if j[str(idq)]["t"] > 0:
j[str(idq)]["t"] -= 1
if j[str(idq)]["t"] == 0:
for cid in allow_channels:
channel = client.get_channel(cid)
message = await channel.fetch_message(idq)
print(f"{cid}")
await message.delete()
del j[str(idq)]
with open("json.json","w") as f:
json.dump(j, f)
OUTPUT:
discord.errors.NotFound: 404 Not Found (error code: 10008): Unknown Message
You're deleting the message inside the for loop
So it successfully deletes the first time, but the 2nd time it'll throw an error because you're trying to delete a message that's already been deleted
So I have this func which I'm calling from both a slash command and a context menu but when I call it the interaction fails bc role is apparently None which I find weird bc I have the exact same code elsewhere applying the role and it's working finepy async def end_further_support(interaction: Interaction, user: Union[User, Member] = None): log.critical(f"Role ID: {client.config.FURTHER_SUPPORT_ROLE}") role = interaction.guild.get_role(client.config.FURTHER_SUPPORT_ROLE) log.critical(f"Role Object: {role}") if role is None: log.error(f"Could not find a role with ID '{client.config.FURTHER_SUPPORT_ROLE}', it's returning 'None'") try: await interaction.user.remove_roles(*[role], reason="User no longer needs further support",) except Forbidden as e: log.error(f"Could not remove '{role.name}' from '{user.name}', bot has insufficient permissions\n{e}") except HTTPException: log.error(f"Could not remove '{role.name}' from '{user.name}', adding the roles failed\n{e}") await interaction.response.send_message(f"Successfully removed {user.mention} from {role.mention}.", ephemeral=True,) but as you can see in the logs it can see the role ID.
Logs: https://paste.pythondiscord.com/mocahasewe
I'm running this on Ubuntu but when I run the code locally on Windows it works fine. This is how I'm applying the role if your curious https://github.com/SnowyJaguar1034/ModMail-FAQ/blob/371d790108d3a8310e4049bf2893360231388b79/classes/fsupport_button.py#L42-L65
!paste
Pasting large amounts of code
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
I have the exact same code elsewhere applying the role and it's working fine
with same bot application? and envs if applicable?
yep to both. figured out my issue tho, Windows could interpret the .env string as a int and pass it to the get_role but Ubuntu was not able to do that background conversion
im using replit free version, and wanna keep the bot alive
i was using this method, but then would get errors i should use a wsgi server
so ive got this script now, but idk how to use uptimerobot to keep pinging the bot
what should i put to the bot send the embed when i make the "/roll"?
Not related to discord bots. Replit is also not a host and we don't recommend using it as one
You might want to ask in #web-development
oh, a freecodecamp vid suggested it
so ubuntu read it as a string?
No way, really?
Well I'll add that to my list of channels to not recommend for discord bots then. That's kind of unfortunate really
yep, which it really is as it's a variable in a environment file but Windows was doing some black magic to convert the string to int without being asked as it knew what type get_role wanted.
i use int over os.getenv(key)/os.environ[key] in these cases just to double check.
oh I was looking at old code that was in 1.7.0
How do you get the icon url in 1.7.0? Is it just ctx.guild.icon_url ?
hey im trying to make something that will print something to the console every time a member joins, from what i understand this is how ur supposed to do it, it doesnt seem to be working for me
client = discord.Client()
@client.event
async def on_member_join():
print('A member joined the server')
!code
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
@slate swan you probably know
why are you in 1.7.0????????
Was running old code
and yes you're correct
can you set guild's icons using that though?
Like icon=ctx.guild.icon_url
theres probably a method for it just check 1.7.0s docs
π₯Ί
docs on mobile is a pain π€
Seems like I need the byteslike object to set the icon
u can
Hello
I'm having difficulties with my Discord Bot...
I'm trying to make a ping command but for some reason it isn't showing up.
no that wouldn't work, It has to be a bytes-like object. so I just made a request to the guild icon url and set the data content as the icon
enable message content intent in the discord developer app
My Main.py file:
import disnake
from disnake.ext import commands
client = disnake.Client()
@client.event
async def on_ready():
print(f'We have logged in as {client.user}')
@client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('Hello'):
await message.channel.send('Hello!')
bot = commands.Bot(
command_prefix='!',
test_guilds=[996245432931995720], # Optional
sync_commands_debug=True
)
bot.load_extension("commands.ping")
client.run('**********')
My ping.py file located in a commands folder:
import disnake
from disnake.ext import commands
class PingCommand(commands.Cog):
"""This will be for a ping command."""
def __init__(self, bot: commands.Bot):
self.bot = bot
@commands.slash_command()
async def ping(self, inter: disnake.ApplicationCommandInteraction):
"""Get the bot's current websocket latency."""
await inter.response.send_message(f"Pong! {round(self.bot.latency * 1000)}ms")
def setup(bot: commands.Bot):
bot.add_cog(PingCommand(bot))
just use bytesio then but i remeber using links there before even currently i am using avatar url it seems to work
I was using discord.py version 1.7.0 though lmao
@gentle sphinx did you enable application.commands scope when inviting the bot?
it was easier to just use requests
It's already enabled. π
How would you do it with bytesio? @shrewd apex
bytesio is not necessary actually i used it coz i needed to use it with pillow
u can just use aiohttp
Indeed π #discord-bots message
set_footer(*, text=None, icon_url=None)
Sets the footer for the embed content.
This function returns the class instance to allow for fluent-style chaining.
Parameters
text (str) β The footer text. Can only be up to 2048 characters.
icon_url (str) β The URL of the footer icon. Only HTTP(S) is supported.
If somebody could help me with my issue that would be most appreciated: #discord-bots message
slash commands dont have cogs do they?
What? I'm confused π
just ignore me i am not sure i havent used slash before
you made a discord.Client instance which youre running
delete the client variable and replace client.run with bot.run and others
I have a question, I'm using Disnake but I'm not sure if there's a better API I should be using or if Disnake is bad. Is there a better API I should be using instead?
\u001b[0;40m\u001b[1;32mThat's some cool formatted text right?
\u001b[1;40;32mThat's some cool formatted text right?
hmm nope
disnake isnt a bad api/api wrapper but if you dont like its structure you can always use other libs like hikari
Well what do you recommend using? π
Well you say 'used' which one do you use now?
sad discord.py noises
i dont do bot development anymoreπ
Ah
so the last lib i used is disnake
I'll give hikari a try and see if I like it better.
its structure is quite good and unique but can be complex if you dont have experience
I first tried discord.py but no.
Yeah Disnake is already challenging for me as a new developer in python so.... we will see how this goes. π
i once asked which is better discord.py or hikari in dpy server they kept talking in circles π€£
I was told discord.py is terrible.
well if its difficult it can be your skill level as these wrappers are advance and use OOP and async
they probably wouldve banned you
they didnt i stopped as soon as i noticed the started giving vague responses rip

gg on still being alive
danny hates other forks for whatever reason
from what i know, (one of the reasons) is because they took out stuff Danny put in and marked the commits as "idk why this is a thing" or similarZ
he hates forks because of their impl which is something you would expect with a public lib
yeah iirc it was related to credits and impl of forks
noone will ever know \πΏ
but clearly he has commited to some so idk
hey i sent this before but didnt get a response hence the repost but im trying to make something that will print something to the console every time a member joins, from what i understand this is how ur supposed to do it, it doesnt seem to be working for me
client = discord.Client()
@client.event
async def on_member_join():
print('A member joined the server')
!intents
Using intents in discord.py
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default discord.py has all intents enabled except for Members, Message Content, and Presences. These are needed for features such as on_member events, to get access to message content, and to get members' statuses.
To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.
Next, in your bot 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
intents = Intents.default()
intents.members = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see the discord.py docs on intents, and for general information about them, see the Discord developer documentation on intents.
on_member_join takes member as an arg
youre missing intents
ill try that now
from discord import Intents
intents = Intents.default()
intents.members = True
bot = commands.Bot(command_prefix="!", intents=intents)
client = discord.Client()
@client.event
async def on_member_join(member):
print('A member joined the server')
still doesnt work
remove the bot variable and pass the intents instance to your client
you can yeah
but youre not using commands so no need
just remove bot and do intents=intents inside of the parenthesis() in discord.Client
and ofc enable the intenr in dev portal if you havent
ah i think that may be my problem
ive tried this before but i havent tried that
still didnt work
remove the bot var and are you running the client?
variable
have you done client.run("Your token")?
have you enabled the intent? and are you running the up to date code?
yes
and are people actually joining so the event gets fired?
ye i keep leaving and rejoining
waitdo i need presence and server members intent
or just message content intent
the server member intent
still doesnt work D:
show your code
are you actually running the client instance? because your code seems fine
and your token is in an env file i suppose?
ah okie
kinda a weird way to do it but it worked at the end of the day
have an on ready event to see if your bot runs
wdym
show your terminal and your code
does it print anything?
well then youll have to wait for the bot to recieve an event
ok im back and this thing is busted
i have this
and when i join it just puts in the console
SnowZillin said
you dont need your bot instance and did you enabled the intent and did you made the event fire?
yes
idk it seems to me like you arent triggering the event
hm
could it be that if i have already joined my server before it doesnt care about on_mem join
do you have the intents enabled?
well i figured it out
its because i lied to you thats why, i had this too
if i get rid of the second client it fixes it
yes remove it
and check the developer portal
its value is being reassigned and you didnt passed any intents
to the Bot class so it wont recieve any events
pardon?
ty for the help
youre welcome
the problem came from me not sharing all of my code
yup
anytime
I am trying to make some changes to my bot. I have it hosted in heroku. but turning on maintenance mode does not get my bot offline. how do I make it offline?
hello
how can i get started making a bot in python?
A tutorial to help you make better Discord bots.
you can also check pins which has some more handy stuff
thanks
you're welcome
is this service safe?
i say you can't trust them
Can't say for sure but i personally wouldn't use it
There are better alternatives available
maybe they're fisher
Thanks for the suggestion!
@bot.slash_command(description = "Your inventory")
@commands.cooldown(1, 10, commands.BucketType.user)
async def inventory(ctx):
if ctx.channel.id != 994308916743782550:
await ctx.respond("You can't use this command here", ephemeral = True)
else:
await ctx.defer(invisible = True)
inventory = await inventory(ctx.author.id, ctx.author.name)
embed = discord.Embed(title = 'Player Inventory', description = f'<@{ctx.author.id}> \n {inventory}')
await ctx.followup.send(embed = embed)
@inventory.error
async def inventory_error(ctx, error):
if isinstance(error, commands.CommandOnCooldown):
msg = f'Try again in {round(error.retry_after)}s'
await ctx.respond(msg, ephemeral = True)
is there any reason why this command wouldn't return any error but just says 'didn't respond'? i tested the inventory function itself and have it after the command
else:
raise error
``` in the error handler
bruh raise is so rude
I am trying to implement slash commands for my bot. but how do I add the library of version 2.0 to my requirements.txt? should I just do discord.py==2.0?
I am gettin the doubt because when I did pip install --upgrade discord.py, it upgraded only to 1.7.3
you will have something like:
discord==2.0
git+https://github.com/Rapptz/discord.py
should work
if i have a list, can i make it vertical in an embed?
can i do something like join \n in my list?
wdym by vertical? something like:
Embed title
My_List:
element_1
element_2
element_3
etc..
should work
I'll try
but in this case, should I also specify git in my requirements.txt?
yeah literally tou will have the package name with version and below it the git link
you will need git installed on your pc
hosting? wtf?
it will be installed if heroku has installed git on his machine, otherwise it will not work
let's see
is there a way to do something like that (to don't make extra function)
from discord.ext import commands
async def some_command(self, ctx):
await ctx.send("it works")
class Cog(commands.Cog):
def __init__(self, client):
self.client = client
@commands.command()
some_command
or only way is
@commands.command()
async def command(self, ctx):
some_command(self, ctx)
?
how i can install dotenv libraries?
self.client.add_command(commands.command()(some_command))
!d discord.ext.commands.Bot.add_command
add_command(command, /)```
Adds a [`Command`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command") into the internal list of commands.
This is usually not called, instead the [`command()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.GroupMixin.command "discord.ext.commands.GroupMixin.command") or [`group()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.GroupMixin.group "discord.ext.commands.GroupMixin.group") shortcut decorators are used instead.
Changed in version 1.4: Raise [`CommandRegistrationError`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CommandRegistrationError "discord.ext.commands.CommandRegistrationError") instead of generic [`ClientException`](https://discordpy.readthedocs.io/en/latest/api.html#discord.ClientException "discord.ClientException")
Changed in version 2.0: `command` parameter is now positional-only.
and use command.cog = YourCogObject
@commands.command()
async def foo(ctx):
...
bot.add_commmand(foo)
foo.cog = YourCog()
thx
i need some help. ive decided to se unix time to show cooldown times instead of using strftime but when i tested it out, it works but the timestamp shows an hour early than the lastest time
Can you show your code?
What would be check for it ?
scroll down i sent it
yes
Ok
https://www.colorxs.com/color/discord-blurple type in the colour you want to get the hex code.
Discord Blurple Brand Color Info - Color Codes (hex rgb cmyk) and Paints, Scheme Combination and Palettes, Images - HEX, RGB, CMYK, HSL HSV/HSB
class discord.FFmpegAudio(source, *, executable='ffmpeg', args, **subprocess_kwargs)```
Represents an FFmpeg (or AVConv) based AudioSource.
User created AudioSources using FFmpeg differently from how [`FFmpegPCMAudio`](https://discordpy.readthedocs.io/en/latest/api.html#discord.FFmpegPCMAudio "discord.FFmpegPCMAudio") and [`FFmpegOpusAudio`](https://discordpy.readthedocs.io/en/latest/api.html#discord.FFmpegOpusAudio "discord.FFmpegOpusAudio") work should subclass this.
New in version 1.3.
@bot.command()
async def play(context):
channel = context.author.voice.channel
vc = await channel.connect()
vc.play(discord.player.FFmpegAudio(source="vc.mp3"))
discord.player.FFmpegAudio(source="vc.mp3")
await context.send("playing a audio")
is True?
Are you getting an error?
The code you sent is not the code from error
but i have error
And yeah you need to play audio differently iirc
how about?
!d discord.FFmpegPCMAudio
class discord.FFmpegPCMAudio(source, *, executable='ffmpeg', pipe=False, stderr=None, before_options=None, options=None)```
An audio source from FFmpeg (or AVConv).
This launches a sub-process to a specific input file given.
Warning
You must have the ffmpeg or avconv executable in your path environment variable in order for this to work.
@free.error
async def free_error(self, ctx: Interaction, error):
await ctx.response.defer()
if isinstance(error, CallableOnCooldown):
reset_hour = round(error.resets_at.timestamp())
cooldown = Embed(
description=f"You have already used your free chance\nTry again after <t:{reset_hour}:t>", color=0xff0000)
await ctx.followup.send(embed=cooldown)```
this is the result it shows
How do you make a discord bot send a tts message? (discord.py)
!d discord.abc.Messageable.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.
The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` parameter must be provided.
To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File "discord.File") object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.10)") of [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File "discord.File") objects. **Specifying both parameters will lead to an exception**.
To upload a single embed, the `embed` parameter should be used with a single [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") object. To upload multiple embeds, the `embeds` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.10)") of [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") objects. **Specifying both parameters will lead to an exception**.
tts kwarg
Get them to create a new app through the dev portal an generate a token, then give them your code.
Thanks zeffo
Might be able to do it through the teams function, not tried it.
Means can you explain?
why do you want to transfer ownership π€
My friend is leaving discord
- Set up a new app in the discord developers portal.
- Give it any permissions/intents required
- Generate a token and apply it to your code.
- remove old bot from server, invite new one.
You really need to speak to your friend first and find out all the details, whats needed, is it even python etc....Then once you have then can then plan out how you will take ownership, manage it, etc.
Hmm
I did that how can I check that reaction is π
You can look at an if statement. something like if reaction.emoji ==
How to do in this?
try:
payload = await bot.wait_for("raw_reaction_add", check=lambda p: p.message_id == message.id, timeout =20)
except:
Working dude, I can't write your code for you unless somsone else can offer. Google is your bf here.
Google gives bad code
Thanks
@discord.ui.button(style=discord.ButtonStyle.gray, emoji=":PepeHeist:") # or .primary
async def blurple_button(self,interaction: Interaction, button: Button):
button.disabled=False
guilds = await get_role()
id = guilds[str(interaction.user.guild.id)]["role"]
mute = interaction.user.guild.get_role(id)
if mute not in interaction.user.roles:
await interaction.user.add_roles(mute)
await interaction.response.send_message(f"I've added <@&{client.role}> role to you!", ephemeral=True)
error:
Traceback (most recent call last):
File "C:\Python310\lib\site-packages\discord\ext\commands\bot.py", line 1329, in invoke
await ctx.command.invoke(ctx)
File "C:\Python310\lib\site-packages\discord\ext\commands\core.py", line 995, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
File "C:\Python310\lib\site-packages\discord\ext\commands\core.py", line 209, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Bot' object has no attribute 'role'
Is it correct?
try:
payload = await bot.wait_for("raw_reaction_add", check=lambda p: p.message_id. == message.id, timeout =20)
if payload.emoji == 'any':
except:
you'll probably have to cast payload.emoji to str, but otherwise should be fine
didn't you want it in your check though?
yeah, so you could just make sure reaction is that in the check and send a message after receiving the event
I was wondering if it possible to access guild count without being there+
is that possible?
Via discord developer is not possible
You can only set or change owner ids in your bot instance so they will have access to commands available only for owners
No, maybe some oauth scope but not with a bot
@bot.command()
async def bm(ctx):
reply = ctx.message.reference
conten = (reply.cached_message or await ctx.fetch_message(reply.message_id)).content
contents = (reply.cached_message or await ctx.fetch_message(reply.message_id))
url = contents.jump_url
auth = contents.author
embf = discord.Embed(title=f"{auth}\nbookmark",color=discord.Color.green())
embf.add_field(name="bookmark message",value=conten,inline=False)
embf.add_field(name="bookmark link",value=f"[link to message]({url})", inline=False)
embf.set_thumbnail(url='https://media.discordapp.net/attachments/993363454519955466/996046786928070696/unknown.png')
embff = discord.Embed(title="bookmark", description="react to π to bookmark the message",color=discord.Color.red())
message = await ctx.send(embed=embff)
await message.add_reaction('π')
try:
payload = await bot.wait_for("raw_reaction_add", check=lambda p: p.message_id == message.id, timeout =20)
if payload.emoji == 'π':
await ctx.send("testing")
except:
await ctx.send("nah")
Guys this command is not sending message on reaction hiw to fix?
Your embed variables are wrong. You set 2 for the same thing, which isn't going to work.
Hello, I make a system of ticket in private message for my bot but I have problems I block to close the ticket in mp directly thanks to a command and how to answer with a command reply directly in mp with the bot but to the person having opened the ticket concerned
i didn't understand nothing 
I'm looking to make a private message ticket system
How to answer the person who opened the ticket with a command knowing that the person does not have access to the ticket
you want to dm the person who ran the ticket command?
can someone please try getting information into a certain guild without your bot being there
if you could try using the api thanks!
you can't
Yes to answer his ticket
what about using their api?
I have already searched the api
neither
, the bot can0t access to all the information
I use discord.py==1.7.3
u can send a dm to the author using the send method on ctx.author
Those are the data that you will not be able to get
@slash.slash(name="ticket", description="Open a ticket to contact the staff")
async def ticket(ctx):
member = ctx.author
guild = bot.get_guild(932745412140482690)
overwrites = {
guild.default_role: discord.PermissionOverwrite(read_messages=False),
guild.get_role(933104717377179680): discord.PermissionOverwrite(read_messages=True),
guild.get_role(933104276320956527): discord.PermissionOverwrite(read_messages=True),
guild.me: discord.PermissionOverwrite(read_messages=True)
}
channel = await guild.create_text_channel(f'Ticket de {member}', category = bot.get_channel(934518633370099783), overwrites=overwrites)
await ctx.send("Ticket crΓ©e")
@slash.slash(name="Reply", description="Reply to the ticket")
async def reply(ctx, message):
if ctx.author
@slash.slash(name="close", description="Close a ticket")
async def close(ctx, channel : discord.TextChannel):
guild = bot.get_guild(932745412140482690)
await channel.delete()```
pain desu ne
This is my code
but can you access people in without being in the same guild?
no, it is written there .-.
it's people on my server
I mean directly access people without being in the same guild?
if you have their id
yes that
!d discord.Client.fetch_user
await fetch_user(user_id, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Retrieves a [`User`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User "discord.User") based on their ID. You do not have to share any guilds with the user to get this information, however many operations do require that you do.
Note
This method is an API call. If you have [`discord.Intents.members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.members "discord.Intents.members") and member cache enabled, consider [`get_user()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.get_user "discord.Client.get_user") instead.
Changed in version 2.0: `user_id` parameter is now positional-only.
!d discord.Guild
class discord.Guild```
Represents a Discord guild.
This is referred to as a βserverβ in the official Discord UI.
x == y Checks if two guilds are equal.
x != y Checks if two guilds are not equal.
hash(x) Returns the guildβs hash.
str(x) Returns the guildβs name.
Are you getting any error handlers/tracrbacks?
No none but it doesn't work, I can create the text channel but not communicate in it
!d discord.Guild.approximate_member_count
The approximate number of members in the guild. This is None unless the guild is obtained using Client.fetch_guild() with with_counts=True.
New in version 2.0.
Ok first of all, to answer the person what do you want to do, DM them or reply in the channel?
I want to reply in private message through the bot
Which one?
So step 1 ) It creates this channel?
Step 2) await ctx.send("Ticket crΓ©e") is this part suppose to amil the author? if yes, does it do what its suppose to? See earlier what Ryuga said, use ctx.author.
can someone quickly post my id here thanks! I can't use my mouse nor my touchpad rn
991178068343390223
thaks
Welcome
Bruh my god
@bot.command()
async def my_command(ctx):
dmChannel = await ctx.author.create_dm()
await dmChannel.send("this is a private message")
Please read your code.
Does anyone know how I could make my discord bot send a random image from a predetermined set of images?
The command to create the channel works, only me and my moderators have access to it
See what Blvck just posted.
You respond with commands so you will need a database/storage method to access that channel id and get it again manually
I want to answer in the ticket room and the bot sends in dm to the person who opened the ticket
it's not like you create a DMChannel in an instance and then the bot knows that you want to respond to that channel in another instance 
Bro i not used 2 times
What code do I need for the database, I have trouble with databases
I don't know how to retrieve information from a database
Learn SQL
it is useless if we just sent to you a random code, you will not even be able to adapt that code to yours, you'll need to learn SQL
I use Sqlite3
So learn
sqlite 3 is SQL 
Yes you have, you have used 2 different variables.
Python comes with sqlite3 already, so its pretty handy to use
hello brad, chillin' around?
Yeah just channel jumping
fair enough
Bro no
A site for a sql doc?
^
embf.add_field(name="bookmark message",value=conten,inline=False)
embf.add_field(name="bookmark link",value=f"[link to message]({url})", inline=False)
embf.set_thumbnail(url='https://media.discordapp.net/attachments/993363454519955466/996046786928070696/unknown.png')
embff = discord.Embed(title="bookmark", description="react to :pushpin: to bookmark the message",color=discord.Color.red())
message = await ctx.send(embed=embff)```
Thanks
Whats wrong in it? Huh
embf = [...]
[...]
embff = [...]
Seriously read it lol. Look at the variables you are using. especially the last 2.
embf and embff are different
i see that but why lmao?
But they are in the same code block.
π
So that's not a problem
btw add this to your code cuz if there is an error the try except block is eating it
and print e?
import sys, traceback
try:
[...]
except Exception as e:
print(f"ignoring exception in {ctx.command.name}\nUnknown error", file=sys.stderr)
traceback.print_exception(type(e), e, e.__traceback__, file=sys.stderr)
Hello. does anyone know how groovy bot managed command permissions with slash commands? I would like to have a set of permissions like this bot, e.g. manage player - only users that have this permission can use commands like player, seek... (I'm using discord.py)
checks works both for application commands and message commands
yep, but the discord doesn't have any way to store custom permissions no? this approach will require to store in some way those permissions in a database no?
It printed nothing
uhm custom permissions are not likely common
wdym by that?
I referred to 'custom' in the sense that I need to store those permissions somewhere.
so I can perform all checking operations
Uhm try to wait for the timeout and tell me if the exception appears
Ok
it depends if those permissions will be equal for all guilds or if the admin of the guild can assign or remove other permissions
@placid skiff i removed the if emoji == pin
And it sent the message but without the emoji check
Ig there is problem with payload.emoji
How it sent the message bruh the check requires a payload which is given from the raw_reaction_add event
try:
payload = await bot.wait_for("raw_reaction_add", check=lambda p: p.message_id == message.id, timeout =20)
if payload:
await ctx.send("test")
are pre-determined, that is, equal for all guilds and the admin will set them to each user.
The pin is unicode right?
then yes you will need to store a db where you declare which permission every guild use
it is a custom emoji?
No
Why use dpy when hata exists
try to add payload.name == :pins:
sorry 
Oh yeah is that, i'm freakin blind lmao
if payload.emoji.name == 'π':
```try with this
Unicode emoji is a str isn't it
is there any cross server chat script
I don't think you can access the text in a users status
The custom activityβs name.
I made a code for the database for the ticket system, I can show it to you to confirm me that there is no error ?
Lol we could check it but the best way is to test it 
why it say's "set_dono_ac" is not defined
Are you in a class
yes
self.set_dono_ac
rather than async def?
No, while calling it
k
that is in a class right?
they should take self ( convention) as first arg
oh btw, how do i use ctx in it?
have a task which loops every x mins and looks for the link in their activity
I can't get the user id of the database to send my message to the user
code?
you are not using ctx in set_dono_ac, why even keep it as param
import os
import sqlite3
class DatabaseTicket():
def __init__(self, database_name : str):
self.con = sqlite3.connect(f"{os.path.dirname(os.path.abspath(__file__))}/{database_name}")
self.con.row_factory = sqlite3.Row
def create_ticket(self, user_id : int, guild_id : int):
cursor = self.con.cursor()
query = "INSERT INTO ticket (user_id, guild_id) VALUES (?, ?, ?);"
cursor.execute(query, (user_id, guild_id))
cursor.close()
self.con.commit()
def reply_ticket(self, user_id : int):
cursor = self.con.cursor()
query = f"SELECT * FROM ticket WHERE user_id = ? AND active = 1;"
cursor.execute(query, (user_id))
result = list(map(dict, cursor.fetchall()))
cursor.close()
self.con.commit()
return result
def close_ticket(self, user_id : int):
cursor = self.con.cursor()
query = f"UPDATE ticket SET active = 0 WHERE id = ?;"
cursor.execute(query(user_id,))
cursor.close()
self.con.commit()```
lol i needed only the part where you retrieve the id but ok
and btw you have more instance of cursor in the same code, you will need to use aiosqlite
!e paginator logic
def foo(list):
pgno = 5
itemper = 3
a = {}
items = []
for x in list:
if len(items) == itemper:
a[pgno] = items
items = []
pgno-=1
items.append(x)
return a
print(foo([1,2,3,4,5,6,7,8,9,123,12,4634,23526,578574,252346456]))
@slate swan :white_check_mark: Your eval job has completed with return code 0.
{5: [1, 2, 3], 4: [4, 5, 6], 3: [7, 8, 9], 2: [123, 12, 4634], 1: [23526, 578574, 252346456]}
!e
a = [1,2,3,4,5,6,7,8,9,123,12,4634,23526,578574,252346456]
print([*zip(*[iter(a)]*3)])
@paper sluice :white_check_mark: Your eval job has completed with return code 0.
[(1, 2, 3), (4, 5, 6), (7, 8, 9), (123, 12, 4634), (23526, 578574, 252346456)]
thanks to peeps at #esoteric-python
π€―
oops
π
!e
a = [1,2,3,4,5,6,7,8,9,123,12,4634,23526,578574,252346456]
print({int((i/3)+1):tuple(a[i:i+3]) for i in range(0, len(a), 3)})
@shrewd apex :white_check_mark: Your eval job has completed with return code 0.
{1: (1, 2, 3), 2: (4, 5, 6), 3: (7, 8, 9), 4: (123, 12, 4634), 5: (23526, 578574, 252346456)}
now fine
mhm
why not this sweet clean code
coz one liners has its own swag
Hahahaha i could not hold me back
lol cool
lmfao
- discord-bots and ot
This suits more with #discord-bots and #ot0-psvmβs-eternal-disapproval
hehe
Yes
imagine being sooooooooo free
imagine not being free even after staying awake 23 hrs a day
stop teasing me π
:spam:
23 hrs? why wasting that 1 hour? that is so much time

sleep is important
casually sleeps for 12hrs
Not when you're developing an app 
More like 18
ya, plus minus 6hrs every now and then
So long as your getting paid for that time, its fine lol!
its not fine if that's affecting you mentally ( totally not coming from someone who sleeps just for 2-3 hr a day)
well my mentality is already broken so why sleep 
Lol, I am made of tough skin, a few hours kip a day does me fine.
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: Donation.get_dono_ac() takes 2 positional arguments but 3 were give
``` error ^
code:
```py
@dono.command()
@commands.has_permissions(administrator=True)
async def add(self,ctx,member: discord.Member,*,amount: int):
if amount > 10000000000000:
await ctx.send("Bro, you can't add that much into my db.")
else:
await self.get_dono_ac(self,ctx.author)
users = await self.set_dono_ac()
users[str(ctx.author.id)]["user_id"] = member.id
users[str(ctx.author.id)]["donated_amount"] += amount
total = users[str(ctx.author.id)]["donated_amount"]
e = discord.Embed(title=f"Donation Added",color=discord.Colour.dark_theme())
e.add_field(name="Amount Added:", value=f"{amount}", inline=False)
e.add_field(name="Total Donations:", value=total)
e.set_footer(text=ctx.guild.name,icon_url=ctx.guild.icon.url)
await ctx.send(embed=e)
with open("donations.json", 'w') as f:
json.dump(users,f)
More like as long as i got food
you dont need to pass self while calling
show get_dono_ac
nvm
Lol you did your best ash, don't worry

If you would have slept you wouldnt be making those mistakes
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: Donation.get_dono_ac() takes 2 positional arguments but 3 were given
dont be like that, I slept for approximately 50 minutes throughout today 
show updated code
Burh it's 4:57 PM and i'm at work 
leave this channel π‘
if ur doing work
avg dc addict
async def get_dono_ac(self,ctx):
user = await self.set_dono_ac()
if str(ctx.author.id) in user:
return False
else:
user[str(ctx.author.id)]["user_id"]
user[str(ctx.author.id)]["donated_amount"]
with open("donations.json" 'r')as f:
json.dump(user,f)
return True
``` this ^
what happened?
just pass in await self.get_dono_ac(ctx)
I grant my availability, but for now client doesn't have any work for me
you have only one argument ctx there, and you're passing 2 arguments ctx.author and user
the fun fuct is that i'm paid for my availability 
Isn't everyone?
you're living my dreams
oh
Can't argue against that, food is great.
gimme name ideas for a command handler
u girl?
lmao
Bruh no
jammyslovehandles
import jammy_love_handles too long init?
Insult to males since they can't do that.
More like import error 
meh
Haha! Nah looks great.
so what should i pass?
i'll name it sparky if i dont get a proper idea 
do what ash said
!e
from ctypes import*
c=lambda _:(i:=(c_char*len(_)).from_address(id(_)+48),setattr(i,'value',b'discord-bot '))
i = 'esoteric-python'
c(i)
print(i)
you sure?
Ashley already said here Samandra.
@paper sluice :white_check_mark: Your eval job has completed with return code 0.
discord-bot
wdym π‘
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: Donation.set_dono_ac() missing 1 required positional argument: 'user'
did what ashley said
show code
import sparky
spam = sparky.send_emoji()
await sparky.wait_for("someone else's message")
await spam.delete()
``` you life in a nutshell, isnt it
ofc needs to be a coro
but im too lazy to write it
π
@dono.command()
@commands.has_permissions(administrator=True)
async def add(self,ctx,member: discord.Member,*,amount: int):
if amount > 10000000000000:
await ctx.send("Bro, you can't add that much into my db.")
else:
await self.get_dono_ac(ctx)
users = await self.set_dono_ac()
users[str(ctx.author.id)]["user_id"] = member.id
users[str(ctx.author.id)]["donated_amount"] += amount
total = users[str(ctx.author.id)]["donated_amount"]
e = discord.Embed(title=f"Donation Added",color=discord.Colour.dark_theme())
e.add_field(name="Amount Added:", value=f"{amount}", inline=False)
e.add_field(name="Total Donations:", value=total)
e.set_footer(text=ctx.guild.name,icon_url=ctx.guild.icon.url)
await ctx.send(embed=e)
with open("donations.json", 'w') as f:
json.dump(users,f)
his life has top level await, its fine
When I run my bot I get an error on the "client.run" line
pass in await self.set_dono_ac(ctx.author)
What error?
you want me to do it again π
what
hold up a second
set not get
||UNIVERSAL TRUTH||
ik
Study
that's why we know 
Allow me ```py
import asyncio
import sparky
async def light_spark():
spam = sparky.send_emoji()
await sparky.wait_for("someone else's message")
await spam.delete()
asyncio.run(light_spark)

Bro, u mean the on_message event?
I wish I could unsee this.
Here is the error message @slate swan
light moe
its dark mode with improper screenshot-ing
change @bot.event to bot.listen()
bro it was a joke , i do know π
read the message panda linked for "why"
everyone hates my [msg,pfp,joke,name]
nah, i personally hate you more than others 
ok
btw @shrewd apex in the credits did okimii really put himself first -> https://gist.github.com/Okimii/0b6e5dcfcfb895ef613ac59a4ecc096a lmao
copy oyur code here https://paste.pythondiscord.com/
,
I don't hate you π«
,
import discord
import random
import list
client = discord.Client()
@client.event
async def on_ready():
print('Bot is online')
@client.event
async def on_message(message):
if message.author == client.user:
return
await message.channel.send(random.choice())
client.run('')
he just wants ppl to dm him 
Your pfp is basically empty lol
Do I need to click save?
you did it worng.
What did you try?
dont insert the event names inside it, you dont need to do that
just replace the .event to listen()
There's a nice spoonfeed
yp then copy the link
And yea, u pinged the wrong person
π« thanks bro
Man really needed 2 paragraphs to explain a presence change π€
Admire the cleanness tough.
@slate swan I sent the wrong code sorry
You still need the . tough
just like ur brain π‘
βΉοΈ
https://paste.pythondiscord.com/umicaconop @slate swan here is the right code
That won't work
L
Panda-beer π³
That's privileged info, need to know basis.
It wasn't
π»
Calm down, stop panicking and take your time. Anyway, are you using replit by any chance?
ur underage
yes I am
π΅ π€
π
Ok, I am not 100% sure how to use/work replit. Think you need to look at running a kill command against the container in the shell, not sure if it can or how it would be done from the discord code.
kill 0 suffices
So bots huh
yeah so why discord
Good news Jammy
delete discord.py 1.7.3 version and download 2.0 or disnake
the bot magically started working again (and I don't remember how I just fixed it)
Did you run what Panda said?
asycio.sleep(60)
Why do we need asynchronous programming?
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!
heyo
i didnt said anything
π«
ye but
π«
it was the reply to this
not saying that time.sleep blocks ur code
!d asyncio.sleep
coroutine asyncio.sleep(delay, result=None)```
Block for *delay* seconds.
If *result* is provided, it is returned to the caller when the coroutine completes.
`sleep()` always suspends the current task, allowing other tasks to run.
Setting the delay to 0 provides an optimized path to allow other tasks to run. This can be used by long-running functions to avoid blocking the event loop for the full duration of the function call.
Deprecated since version 3.8, removed in version 3.10: The `loop` parameter. This function has been implicitly getting the current running loop since 3.7. See [Whatβs New in 3.10βs Removed section](https://docs.python.org/3/whatsnew/3.10.html#whatsnew310-removed) for more information.
Example of coroutine displaying the current date every second for 5 seconds:
You are sleeping the bot with time.sleep, that is a blocking call.
ye
basically that time.sleep(60) stops your bot for 60 seconds, so it will not respond to any commands or events for that duration
Either remove time.sleep(60) to make it instant or use asyncio.sleep(60)
yes
!d asyncio
Hello World!
import asyncio
async def main():
print('Hello ...')
await asyncio.sleep(1)
print('... World!')
asyncio.run(main())
```...
ya you need to import asyncio
π
You need to await it
did u await?
did you await it?
um let me check
asyncio.sleep is a coro
!async-await
Concurrency in Python
Python provides the ability to run multiple tasks and coroutines simultaneously with the use of the asyncio library, which is included in the Python standard library.
This works by running these coroutines in an event loop, where the context of the running coroutine switches periodically to allow all other coroutines to run, thus giving the appearance of running at the same time. This is different to using threads or processes in that all code runs in the main process and thread, although it is possible to run coroutines in other threads.
To call an async function we can either await it, or run it in an event loop which we get from asyncio.
To create a coroutine that can be used with asyncio we need to define a function using the async keyword:
async def main():
await something_awaitable()
Which means we can call await something_awaitable() directly from within the function. If this were a non-async function, it would raise the exception SyntaxError: 'await' outside async function
To run the top level async function from outside the event loop we need to use asyncio.run(), like this:
import asyncio
async def main():
await something_awaitable()
asyncio.run(main())
Note that in the asyncio.run(), where we appear to be calling main(), this does not execute the code in main. Rather, it creates and returns a new coroutine object (i.e main() is not main()) which is then handled and run by the event loop via asyncio.run().
To learn more about asyncio and its use, see the asyncio documentation.
enough
It's info π
ikr
i just forgot 1 await
dont you ever did that mistakeπ
I've had this error for 10 minutes
when you come up with quick fixes like that, you probably experienced a similar problem before so you know how to tackle it
do (user_id, )
try (user_id, )
ye but that also starts from 0
it requires an iterable, so (object, ) makes a tuple
(object) doesn't
wdym by starts from 0?
for database_ticket.reply... or cursor.execute ?
execute
ok thanks I go test
we get the error first
leave it
β
What data type is user_id and what did you define the column as?
I recommend using type()
To be certain.
What db is this?
Okay so ID's are in the right range.
Uh hunter
I suspect that the id is a string or something.
you're alive 
Indeed
@slash.slash(name="Reply", description="Reply to the ticket")
async def reply(ctx, message):
user_id = discord.Member
database_ticket.reply_ticket(user_id)
embed=discord.Embed(title = "Ticket", inline = False)
embed.add_field(name = "Message", value = message)
embed.set_footer(text=f"By {ctx.author}")
await ctx.send(embed=embed)```
bruh you can't save Member object to a database lmao
def reply_ticket(self, user_id : int):
cursor = self.con.cursor()
query = f"SELECT * FROM ticket WHERE user_id = ? AND active = 1;"
cursor.execute(query, (user_id, ))
result = list(map(dict, cursor.fetchall()))
cursor.close()
self.con.commit()
return result```
You need an object relational mapping database to save objects, and they're harder than sqlite 
no don't recommend that
Just use the id.
Bruhhh
since you can retrieve objects from their ID
Just store the info you need.
user_id = ctx.author.id this is how you should do
sqlalchemy 
how is that related
?
he's talking about the data type which is getting saved, not an ORM
object relational mapping database
same thing uhhh my bad
but how is that any different
more like I just read half the convo tbh
Now how can I get the bot to send the message privately to the member who opened the ticket?
sqlite can't save a literal Object
like a discord.Member
.
!d discord.User.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.
The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` parameter must be provided.
To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File "discord.File") object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.10)") of [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File "discord.File") objects. **Specifying both parameters will lead to an exception**.
To upload a single embed, the `embed` parameter should be used with a single [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") object. To upload multiple embeds, the `embeds` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.10)") of [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") objects. **Specifying both parameters will lead to an exception**.
We've answered to that this morning 
timezones
Using the id stored in the database of the person who opened the ticket ?
you're right:
We've answered to that like 7 hours ago
apologies accepted 
I am lost after almost 8 hours of programming
when did I say it can
i'm lost after 2 hours lmao
When i was developing the project for my graduation exam i had something like sessions of 6 hours or more 
i've programmed for 10-12 hours in a row before with only breaks to pee and coffee
And most of the time was:
me: coding for 2 hours*
me: reading what i wrote*
also me: "What the fuck did i just write?"
thats why comments are soo important
why the bot doesnt send the embed on the chat when i use the command?

you need to respond to the interaction
embed = ...
await interaction.response.send_message(embed=embed)

pandabear is pandabweer or what
π§’
no different
πΊ
no
bear = π»
beer = πΊ
Yeah but you know i was a little dev who barely knew how to use pointers in C
it's fun when you get really into it
isn't that dog
the indent is wrong at embed by looks of it for starters... needs to be 3/4 spaces I believe
i still dont know how to use pointers π
bro what
Meh, going to take a while getting use to that.
discord.idents π
bro π , hover over the emoji
Well I have to, otherwise my teacher will hunt me down π
under the "embed = "?
yes??? thats how indentation works
your teacher will reference you then point you out of the class
ty
Never used that describe bot before, so knowing all its commands is not my thing.
πΆ π»
never gonna believe a single person about such crap here
now its like this
if you never enjoy coding why do you do it
bro π my terminal does better indentation work than replit
embed = discord.Embed(
await interaction.response.send_message()
)
and color = discord.Color.blue()
I do enjoy it, but who sits continuously for 2 hours unless you really have to and there's a deadline in near time
poor spinal cords 
i once woke up at 3 am, made a game for like 3hrs then slept again
when you're in the zone
5 hours can pass before i even realise
i wish i could get into that frame of mind more often
why even sleep 
i cant even think when i wake up
ew
pardon
cats
uwus

your bot stats, uptime chart and most importantly cats like zeffo said
these some good ideas, especially cats, do you think it's too much to make every button a cat
def not
put me 
Use mira jane as the logo for the site...
π₯±
coding it from scratch with bootstrap and flask
first time doing everything like this
flask ewwww
im gonna do optional ad videos eventually for one of my bots, got the discord login system done for it so far
I have been looking into django personally for a backend to connect my bot to one day....
django is certainly uwu
uwu? Lol sorry no good with slang!
what's wrong with flask
django has an async interface so it's absolutely better
ooo
django is way too overkill for this
We don't talk about java||shit|| here 
i swear, every time i start something new i somehow choose the wrong options for everything
,
sad
Yeh seen a lot of recommendations on django to use with discord bots thats why I added to my own project list. First stage get a standard bot working and upskill in my python, then move into SQL then connect it to web app.
yeah probably, i doubt even if my bot was huge i'd have enough simultaneous visitors for it to matter, would've been nice to just start with that tho
i've done css before, still hate everything about front end
use fastapi π
i wish i could write everything in python, hate html too
!pypi websockets --- no u
let's use you 
so sus
write a transpiler to every language written in python π§
I can say the same for css
I HATE css
yeah it doesn't seem that hard but really finicky
for no reason
css and html aren't bad, they're just hard and frustrating a lot of the time
another reason to stick to backend
me
anyway imma play some fn π peace
ew imagine playing fortnite
smh
text-align/margin exists
google exists
stackoverflow 
what bots have websites that i can get inspiration from 
just keep adding whitespaces ;-; and align it manually
dyno
carl
js 
php is love, php is life β€οΈ fk js
im gonna try and do the whole website without writing a single line of js 
not too hard cuz they allow that
try doing the same in python
rust is something other languages can never be, change my mind 
just like you 
Ashley β Today at 19:23 
hmm, when should you shard a bot
upgrade it/get another drive
Use the tree size app, find where the larger directories/files are, remove them if possible.
1k guilds min recommended
Off-topic channel: #ot2-never-nesterβs-nightmare
Please read our off-topic etiquette before participating in conversations.
One of my bots is at 1.2k but doesn't seem to be having any problems 
Then it's ok to go without shards until it faces performance issues
Wasn't it 2000 or 2500 for sharding?
class discord.AutoShardedClient(*args, intents, **kwargs)```
A client similar to [`Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client") except it handles the complications of sharding for the user into a more manageable and transparent single process bot.
When using this client, you will be able to use it as-if it was a regular [`Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client") with a single shard when implementation wise internally it is split up into multiple shards. This allows you to not have to deal with IPC or other complicated infrastructure.
It is recommended to use this client only if you have surpassed at least 1000 guilds.
If no [`shard_count`](https://discordpy.readthedocs.io/en/latest/api.html#discord.ShardInfo.shard_count "discord.ShardInfo.shard_count") is provided, then the library will use the Bot Gateway endpoint call to figure out how many shards to use.
Ah okay
!e
"""Scene \{
// normalized rgb triplet
background_color: (1, 0, 0)
// 3d vector representing camera's position
camera_position: ({0}, {1}, {2})
// field of view in degrees
field_of_view: 70
\}""".format(1, 1, 1)
@slate swan :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 8, in <module>
003 | KeyError: '\n // normalized rgb triplet\n background_color'
but why here
go to #bot-commands

hi what it isn't work?
@client.command()
async def clear(ctx, amount = None):
if amount == None:
await ctx.reply('``π§`` correct use: `+clear {ammount}`')
else:
await ctx.channel.purge(limit = amount)```
@sick birch
Does anyone know how I can deal with this problem?
In other words
How do I stop my discord bot from exceeding rate limits?
is that replit?
yes
thats a common issue for bots running on replit since there's plenty of them running on the same datacenter
@hushed galleon know u? π¦
u know
are you getting any error in the terminal when you try using the command?
+clear working but +clear 10 no work
im using heroku and github to host my bot
is there a way to use a database with that?
You need amount: int
that would be because you tried passing a string to the limit= parameter; command arguments are read as strings by default, but to have dpy convert your "10" into an actual python integer, 10, you need to typehint your amount parameter with int
coincidentally the f' is missing as well
uhhh where
@client.command()
async def clear(ctx, amount = None):
if amount == None:
await ctx.reply('``π§`` correct use: `+clear (ammount)`')
else:
await ctx.channel.purge(limit = amount)```
before the string like f' ... {...}'
and type hint amount with int as mentioned
Probably not a good idea to work with discord.py already then
@client.command()
async def clear(ctx, amount: int = None):
if amount == None:
await ctx.reply(f'``π§`` correct use: `+clear {ammount}`')
else:
await ctx.channel.purge(limit=amount)
its advised to learn python before making discord bots because they are fairly advanced, so take sometime and get the basics down
By default without any typehints, discord.py won't parse any user arguments and will return them to you as a regular string. That's why it won't be an int
And let's not spoonfeed in the future, please
sorry
np
Hello. So I am making some CAD system RP bot (Roblox stuff)
But the point is that it says command not found
import nextcord as discord
from nextcord.ext import commands
intents = discord.Intents.default()
intents.message_content = True
client = commands.Bot(command_prefix='.', intents=intents)
client.command()
async def backup(ctx, *, unit = None, location = None, reason = None):
embed = discord.Embed(title="Backup Needed!", description=f"Attention all units, {unit} needs backup. ||<@&996463467471065159>")
embed.add_field(name="10-20", value=location)
embed.add_field(name="10-31", value=reason)
ctx.send(embed=embed)```
no worries, happens
Isnt it supposed to say the unit name, Then under 10-20 should be location and 10-31 should be Reason
@client.command()
async def backup(ctx, *, unit = None, location = None, reason = None):
embed = discord.Embed(title="Backup Needed!", description=f"Attention all units, {unit} needs backup. ||<@&996463467471065159>")
embed.add_field(name="10-20", value=location)
embed.add_field(name="10-31", value=reason)
ctx.send(embed=embed)```
well you are defaulting location to None
Yeah
Idrk how that thing works
since u also have the * operator, I am pretty sure it's eating up all the values for unit and location is None
try printing unit
print unit and tell me what it says
I believe u want unit to just be that 4 digit number, but as u can see from the embed it contains the reason + location
Yes
what u need to do is remove the *, and when u use the command, u dont supply it commas,
Ok
also since the reason can contain spaces, u can do *, reason=None
something like
async def backup(ctx, unit = None, location = None, *, reason = None):```
use 3 `
well I think there's a way for that as well but I haven't done dpy in a while so im not sure
Oh ok
Well anyways thanks, Im happy with this for now
okay
I'm aware, it was a typo
Lol
trying to make an embeded message but it doesnt seem to be working? @client.command() async def embed(ctx): embed = discord.Embed(title = 'EndoBot Commands', description = 'This is a list of commands to use with EndoBot! ', color = discord.color.blue()) embed.add_field(name = 'General Commands', value = 'do Hello (Say Hello to the bot), do Bot (Says Bot Description), do Help (Says how to use the Bot and its features)', inline = true) embed.set_thumbnail(url = 'https://cdn.discordapp.com/attachments/996104926264565862/996456504033017896/BOT_NAME_1.png') await ctx.send(embed=embed)



