#discord-bots
1 messages Β· Page 957 of 1
i mean yo ucan it has nothing and if u get it working i ll reset it π
Haha
Hey @ripe harness! I noticed you posted a seemingly valid Discord API token in your message and have removed your message. This means that your token has been compromised. Please change your token immediately at: https://discordapp.com/developers/applications/me
Feel free to re-post it with the token removed. If you believe this was a mistake, please let us know!
aw
lol
wait yea 2
my bad. hmmmmmm, can u post the part of the token preceding the first period?
OTYwODcwODU2NjMwODgyMzA0
do you want the mid one π
return connected["NightmareFever"]["Config"].find_one({"name":entry})["token"]
there is my token see if u can use it
It's a blank example just on ready func and this token and it is bullying me

y
oh wow
Hmm

weird, try resetting the token and copying again
did it 5 times π¦
prolly it isn't being copied and u r pasting the old token
This message here should be ephemeral
For whatever reason it isn't
This also applies to my error handler
Which is here:
import traceback
from io import StringIO
from typing import Union
import discord
from discord import Interaction, app_commands
from discord.app_commands import AppCommandError, Command, ContextMenu
async def on_app_command_error(interaction: Interaction, command: Union[Command, ContextMenu], error: AppCommandError):
error = getattr(error, "original", error)
match error.__class__:
case app_commands.CommandNotFound:
return
case app_commands.MissingPermissions:
msg = "__This command requires the following permissions:__\n**{}**".format(
"\n".join(i.replace("_", " ").replace("guild", "server").title() for i in error.missing_permissions)
)
case app_commands.CheckFailure:
msg = str(error)
case _:
f = discord.File(StringIO(traceback.format_exc()), filename="exception.py")
await interaction.response.defer()
return await interaction.followup.send(file=f, ephemeral=True)
return await interaction.response.send_message(msg, ephemeral=True)
Hm
!d discord.Interaction.followup
Returns the follow up webhook for follow up interactions.
It's a webhook
ah
Wait nvm
Interesting
Yeah make sure it's a WebhookType.application
BTW @sick birch any idea how discord handles ratelimits for slash commands and context commands since we still need to defer and stuff so does deferring also count as a ratelimiting request?
Why this is interesting
On some commands the ephemeral followup send works, others don't
Here's the commands source code
why use followup
WebhookType.application
hm it does print the correct type
oh its dpy, dunno how its apcs work π
I mean, it works the same as other forks'
wait, its a slash command nvm
Ben.
lmao
Funniest shit I have ever seen
Lmao some people do be remembering old cartoons
I mean, I send those in my bot...
what measures would you guys suggest for anti-raiding functionality
He drug dealer of talking tom
!custom_cooldown
Cooldowns in discord.py
Cooldowns can be used in discord.py to rate-limit. In this example, we're using it in an on_message.
from discord.ext import commands
message_cooldown = commands.CooldownMapping.from_cooldown(1.0, 60.0, commands.BucketType.user)
@bot.event
async def on_message(message):
bucket = message_cooldown.get_bucket(message)
retry_after = bucket.update_rate_limit()
if retry_after:
await message.channel.send(f"Slow down! Try again in {retry_after} seconds.")
else:
await message.channel.send("Not ratelimited!")
from_cooldown takes the amount of update_rate_limit()s needed to trigger the cooldown, the time in which the cooldown is triggered, and a BucketType.
ah that way
Ben.
Yes 
lmao ngl Ben 10 > Talking Ben for whatever reasons
But won't continue this talk here
No
I love ben10 too π anyways ot
Nope
is there a specific channel for d.py support or would it just be the regular help channels?
Try your luck in https://discord.gg/dpy and best of luck getting an answer without someone bullying u!
This channel is meant for the same
so positive about bullying problems, how sweet
and that exclamation mark made it all more worse
I used to hang out in the help channels of that server most of the time when I was new to bot making, so ik the pains π€·
Same
Its not that bad
no comments about them after what yerlikaya showed yesterday π asking for help there is like extra hell
PoV: You are a bot dev who dk what are functions and smth like classes also exist
"extra hell" Well, a bit mild but no comments
i do think the expectation there of learning OOP and fundamentals is higher
They just want people to understand python beforehand
Well from my experience, they don't like beginners and only help those people whole heartedly who are good in Python
And rightly so
I mean some people do help beginners but still π€·
few
some is a strong word to say here
Haha
Here?
Dpy server
in dpy server no one will help you without basic knowledge
- We're glad to help where we can, but come with at least a basic understanding of Python.
- It's recommended to complete a smaller project first. Some of the techniques used in the library are difficult for beginners to understand and could be potentially frustrating or confusing.
- For a more nuanced definition, please check faq
I got ample of experience and second this statement
I will just join back and annoy them now
discord.py actually fueled me with the motivation to continue learning Python
I do not condone that
aka "Mute Speedrun"
Same
yeah my experience in dpy's server ranges wildly, most of the time I end up with more problems than i started with unless I'm going there for a very specific very niche problem, the handful of times I've received decent support have alwys been when Danny is online and in one of the help channels, then they are all helpful
There's a new help channel for more advanced discord.py/Python issues there now
lmao, I have nothing to do with the server so i might just make the most out of it
right
Still
You do you
Saw it, good decision for people who know Python but that just draws a wider line between beginners and advanced, sooo idk how to react ngl
I mean, I myself learnt most of the stuff by looking in the help channels
When you use an consumable object in your discord bot game that collects materials for you and for some reason enemies around you start exploding too 
what

fun fact, i have somewhere, a channel where i take bits of code that i find interesting from help channels and when i'm out of ideas i just scroll through those and based on those ideas i do something different 
i can just tell this bug is going to be an ~ordeal~ to fix
My phone gallery: 14500 pics
10000 pics: Screenshots from different help channels about different stuff
4500 pics: Memes
do you even have a single picture of yourself
i would never
does that mean i am allowed to ask here?
Prolly like 5, max
Yup
i have a backup storage drive with all my memes on it π
ok awesome
Hahaha well I am too lazy to rearrange all the code pics and memes into different albums
im trying to make my bot run an ffmpeg command using the ffmpy library, but everytime it does, the entire bot stops doing anything until its done, i've tried putting it into an async function and await it but that didn't work, does anyone have any suggestions to get around this?
and yea, also make space for some school work pics out of those code pics
π sad
!blocking
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!
Better I don't
lmao
This is what is happening with your bot @wary hatch
use VoiceChannel.connect and VoiceClient.play with opus or smth idk
shouldn't be blocking then
i did exactly this, but it still waits
Show code
okedoke
ngl, i find voice stuff quite troublesome. ffmpeg and stuff like this damn, better just give up
true, but I am still waiting for voice receive in disnake 
disnake
Pretty sure the websocket does dispatch that information, does it not?
just use some external library to make voice commands
async def fix_vid(input):
ff = FFmpeg(
inputs={input: None},
outputs={f'new_{input}': '-c:a copy -c:v libx265 -crf 20'}
)
ff.run()
return
await fix_vid(input)
this is everything relevant, the fix_vid call is in an on_message event that grabs an attachment and saves it, didn't think it'd be necessary to send since it's quite large
Yup it does, djs already has it since a few versions
EQ has been busy with irl stuff so he isn't able to spend time on lib dev
Ever heard of loop.run_in_executor?
i have not
π
I, uhhh, why r u using the FFmpeg wrapper?
EQ is a cool guy no cap
Yup
cause im dumb, probably. not even sure what ffmpeg wrapper means tbh
show yr imports
What are you using ffmpeg for?
import discord
import os
import urllib.request
import asyncio
import subprocess
from ffmpy import FFmpeg
from discord.ext import commands
grab video, run some magic on it, send it back
But anyways, either way, make it an async function and use loop.run_in_executor where loop = bot.loop
!pypi ffmpy
I see
"simple" ofc
Why not put that in a seperate application? like flask or something
then just use aiohttp and you won't worry about having it block
I don't think its maintained anymore tho
cause i don't know what flask is

!pypi flask
Well. Perfect oppurtunity to learn
PoV: Multiple concurrent requests are made and the web server crashes
flask is lovely easy
the thing you use for storing liquids
If you make it so only you can use it, that shouldn't be a problem
Or, if you know JS/TS already you can use express if you'd like
What if that command is used by multiple people at once?
Stop with chem, go Pythonic
i dont understand how flask is relevant to my problem
@sick birch gonna shed some light on this
not a diss to you, i am just unfamiliar
Go 
nah, just talking about a normal flask, I dropped chem an year ago, i remember nothing
Stop it, I hate Go
but go 
how do i set the author image again?
i forgor π
Long story short, it is a module used to make websites and APIs
(on an embed)
!d discord.Embed.set_author
set_author(*, name, url=None, icon_url=None)```
Sets the author for the embed content.
This function returns the class instance to allow for fluent-style chaining.
Have the heavy lifting (video processing) on the backend
can i not do it in the constructor?
And use aiohttp to wait for server response
me not like using embed functions
!d discord.Member.avatar
property avatar```
Equivalent to [`User.avatar`](https://discordpy.readthedocs.io/en/master/api.html#discord.User.avatar "discord.User.avatar")
!d discord.Asset.url
property url```
Returns the underlying URL of the asset.
(:
sooo it would just make the bot send a request to a different program running?
I will just go away
Yea, prolly he means IPC or smth
uhh discord.Embed.set_author is a function?
ah mb its a method
method
is there any objectivity to whether i should use flask vs loop.run_in_executor
I would prefer the second one
bro scroll up
They do return Trueself
πΏ
discord.PermissionOverwrite(discord.Permissions.all==False)
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 384, in _run_event
await coro(*args, **kwargs)
File "/home/runner/cogs/events.py", line 200, in on_command_error
raise error
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 182, in wrapped
ret = await coro(*args, **kwargs)
File "/home/runner/cogs/owner.py", line 175, in setupbot
guild.default_role: discord.PermissionOverwrite(discord.Permissions.all==False),
TypeError: __init__() takes 1 positional argument but 2 were given
i mean they return the objectπΏ
/home/runner - don't use replit
the instance, yes
just waiting for the time when dpy drops support for 3.8
I swear 3 people asked their questions in the dpy server and never got an answer there and came here in the past 10 mins
dpy server > pydis
Yea
Sometimes the opposite also happens π
Don't u think IPC would be a better way?
Is that really needed
I hardly see someone getting ignored here ||much|| though
A simple http request will do
I mean, whenever its day time here, this channel is mostly dead
Hardest part is figuring out how to transmit non text data
asyncio.loop.run_in_executor sounds
binary format π
Too much work receiving binary and decoding it both the client and API side but then, run_in_executor is the easiest way
makes me remember some shit i did in my first image api
Files can be sent in post requests
Or you can serialize the image into an array containing the rgb values of each pixel
when making the loop thing, what would i set the loop to?
Uhh stop before I start to question my decision to start programming
bot.loop
nvm internals
i tried that and it said not defined
i need a bot that will say a random member when i ask it to
!d random.randrange
random.randrange(stop)``````py
random.randrange(start, stop[, step])```
Return a randomly selected element from `range(start, stop, step)`. This is equivalent to `choice(range(start, stop, step))`, but doesnβt actually build a range object.
The positional argument pattern matches that of [`range()`](https://docs.python.org/3/library/stdtypes.html#range "range"). Keyword arguments should not be used because the function may use them in unexpected ways.
Changed in version 3.2: [`randrange()`](https://docs.python.org/3/library/random.html#random.randrange "random.randrange") is more sophisticated about producing equally distributed values. Formerly it used a style like `int(random()*n)` which could produce slightly uneven distributions.
Deprecated since version 3.10: The automatic conversion of non-integer types to equivalent integers is deprecated. Currently `randrange(10.0)` is losslessly converted to `randrange(10)`. In the future, this will raise a [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "TypeError").
does it matter if its in a cog?
self.bot.loop
or ctx.bot.loop
aaaaaaaa i did it and it still doesnt work aaaaaaaaaaaaaaa!!!!
async def fix_vid(self, input):
ff = FFmpeg(
inputs={input: None},
outputs={f'new_{input}': '-c:a copy -c:v libx265 -crf 20'}
)
loop = self.client.loop
loop.run_in_executor(ff.run())
return
so i goofed here right
yes
i knew it
u need to do
def fix_vid(self, input):
ff = FFmpeg(
inputs={input: None},
outputs={f'new_{input}': '-c:a copy -c:v libx265 -crf 20'}
)
ff.run()
And then, in yr command, do self.bot.loop.run_in_executor(None, fix_vid, "some vid file prolly")
!d asyncio.loop.run_in_executor
awaitable loop.run_in_executor(executor, func, *args)```
Arrange for *func* to be called in the specified executor.
The *executor* argument should be an [`concurrent.futures.Executor`](https://docs.python.org/3/library/concurrent.futures.html#concurrent.futures.Executor "concurrent.futures.Executor") instance. The default executor is used if *executor* is `None`.
Example:
yea
do i await self.bot.loop.blahblah?
yes
still at ffmpeg stuff huh
it works!!!!!!!!!! thank you!!!!!!!!! 
cool!
with or without blank spaces in code 
be a chad and format it in black
but it does format itπ³
yeah it's in black format rn
good
50% of the time you ask coders a question they go on a tangent smh
and no new lines is better
@slate swan can u help the person in #help-carrot?
no
wheres the pep8 guy
plz
im eating π
plzplzplzplz
@final iron
oh wow
mine is 1am
He lives in USA or smth idk
it's 0:27 there rn
Yea
u English or smth? π
no
not particularly
actually, I'm frankly far away from the land of the British
jk literally one country away
!ot
Off-topic channel: #ot2-never-nesterβs-nightmare
Please read our off-topic etiquette before participating in conversations.
attributes = {
'name': "commands",
'aliases': ["help", "helps"],
'cooldown': commands.Cooldown(1, 3, commands.BucketType.user),
'hidden': True
}
help_command = HelpCommand()
help_command.command_attrs = attributes
exception
Traceback (most recent call last):
File "", line 16, in <module>
'cooldown': commands.Cooldown(1, 3, commands.BucketType.user),
TypeError: Cooldown.__init__() takes 3 positional arguments but 4 were given```
anyone know why?
ah wait
from 2.0 on cooldown no longer has type as an argument right
Hi
need to use cooldown mapping
No, 2:57 when you said that
canada*
HUH
what
pm
dont ask how i know he lives there π³
but I was talking about india
Oh
there's no way
π€¨
@final iron #discord-bots message 
Looks fine but I don't know why you're adding on to desc
Personally I like the newlines
I think it would be harder to read without them
i could have it all on one line but with an f string it would be one long line and less easily readable
how can i get the message of the user that invoked a help command?
i'm subclassing commands.HelpCommand
all pep8 says is use them sparingly 
i want the bot to reply to the message instead of sending the help embed to the destination
await ctx.message.reply(embed=embed)
you probably need to find whatever id the message is that you want, fetch the message and then do <message you fetched>.reply(stuff)
won't work
why?
it does
yeah
self.context
wait what
how else will you send the message lol
!d discord.ext.commands.HelpCommand.context
The context that invoked this help formatter. This is generally set after the help command assigned, command_callback(), has been called.
get_destination() ?
class User:
def __init__(self, bot, user_id: int, name: str, role: Role):
self.bot = bot
self.user_id = user_id
self.name = name
self.in_game = False
self.isBot = False
self.role = role
How would I make it so that upon init this class identifies which role a user has
you need a message object to reply to...

i mostly just use new lines on endings of actions so if elif and else have a new line between them and try and except blocks and for loops etc
oh yeah -_-
get_destination returns a TextChannel
ok well thanks guys
i tried that but too much space 
this is probs about the same amount but depending on complexity
well thats just what i do for better readability and everything is organized yk
but if statements already have an indentation which is kind of a natural separator, at least that was my thinking
How to send custom emojis?
if it's in the same server i think theres some text thing you can send, can't remember
Same server.
possibly something like that
I did like that. Not working.
just fetch whatever emojis you need at the bot startup and keep in a list or dict, it's what i do
doesn't take any time
yes but if theirs conditions on top it would get smashed together making it a bit harder to read

if a > b:
print(1)
elif a < b:
print(2)
compared to this
if a > b:
print(1)
elif a < b:
print(2)
Makes 9 lines of blank space for 31 lines of code
i guess it's just one if statement logically connected to the above code then it doesn't need a space
so 8
instead of 5
looks good to me but the lines in the variables are a bit unnecessary
what's player.inventory
it's the players inventory 
it's a flat dictionary that is unpacked into a db when it saves
ok
otherwise my player class would be dumb af
because there are like over 20 inventory items, and variable prices
for each item
Would anybody like to help me with training an antispam model
For the future antispam bot
I need some samples of spam and not spam
To be more exact around 1k
how do u make a hyperlink in a text
It's something like [text](link) or vise versa I always confuse it
like "hey u cant do this and this watch (hyperlink)this to do verify urself"
Works only in embeds
okay ty
Look at markdown syntax for that
And context and slash commands (webhooks)
Ok
square first then round second
Lmaoo everyone is confused in this thing istg
what is the logical reason that one is square and one is round?
Idk
ultimately it comes down to the shapes and patterns that humans have found in nature
ah yes, the square bracketed plant species as we all know
Hey guys, I have a question.. There is this bot written in JS, I offered to assist but I use dpy with nextcord fork.. is it possible to write a command in another pro lingo?
πΏ so you want python help with a js bot
Heard it was possible
No not help, just asking if i could use another language
πΏ
what exactly are you looking for
there's three different things you've mentioned: the discord.py library, the discord.js library, and the discord API
Knowing discord.py and the discord API doesnt immediately translate into knowing how to write javascript code using discord.js, but they do borrow similar concepts like Members/Users, Embeds, Messages, etc. so you will find it somewhat easier to learn how to use discord.js
lmfao
if you're playing around with the doc commands you should use #bot-commands, or you can ask us what you need
Oh
trying to find syntax for something like
class discord.Member```
Represents a Discord member to a [`Guild`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild "discord.Guild").
This implements a lot of the functionality of [`User`](https://discordpy.readthedocs.io/en/master/api.html#discord.User "discord.User").
x == y Checks if two members are equal. Note that this works with [`User`](https://discordpy.readthedocs.io/en/master/api.html#discord.User "discord.User") instances too.
x != y Checks if two members are not equal. Note that this works with [`User`](https://discordpy.readthedocs.io/en/master/api.html#discord.User "discord.User") instances too.
hash(x) Returns the memberβs hash.
str(x) Returns the memberβs name with the discriminator.
if ctx.message.id
ah ok whatever
??
π€ wait he sking for author id
πΏ
member and author has the same attributes
alright.
and itll give me the number?
it should
well, the specific code you would write depends on where the author comes from and what you named your parameter
it will work, if it's inside a command that inherits ctx
ok
channel = ctx.guild.get_channel(699577970117050399)
messages = await channel.history(limit=None).flatten()
for i in messages:
with open("stuff.txt", "w") as wf:
wf.write(i.attachments)``````
Ignoring exception in command get:
Traceback (most recent call last):
File "C:\Users\nikit\PycharmProjects\huhh\discord\ext\commands\core.py", line 186, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Users\nikit\PycharmProjects\huhh\docs\main.py", line 206, in get_all_images
messages = await channel.history(limit=None).flatten()
AttributeError: 'NoneType' object has no attribute 'history'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\nikit\PycharmProjects\huhh\discord\ext\commands\bot.py", line 1183, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\nikit\PycharmProjects\huhh\discord\ext\commands\core.py", line 905, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
File "C:\Users\nikit\PycharmProjects\huhh\discord\ext\commands\core.py", line 195, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'history'```did they change something?
i had the lines for it in my automated bot that i learned went against tos so i deleted code without thinking
that the stuff in there could be useful.
that error indicates your get_channel returned none; where/when is this code running?
in a command
did you double check the id?
also are you using your command only in the guild that has the channel?
yeah
wait no
Traceback (most recent call last):
File "C:\Users\nikit\PycharmProjects\huhh\discord\ext\commands\core.py", line 186, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Users\nikit\PycharmProjects\huhh\docs\main.py", line 207, in get_all_images
messages = await channel.history(limit=None).flatten()
AttributeError: 'async_generator' object has no attribute 'flatten'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\nikit\PycharmProjects\huhh\discord\ext\commands\bot.py", line 1183, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\nikit\PycharmProjects\huhh\discord\ext\commands\core.py", line 905, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
File "C:\Users\nikit\PycharmProjects\huhh\discord\ext\commands\core.py", line 195, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'async_generator' object has no attribute 'flatten'```give me this now
@hushed galleon
hm i havent seen async_generator come from channel.history()
whats your code now if you changed anything, and what version of dpy are you using?
async def get_all_images(ctx):
guild = bot.get_guild(699577686795747349)
channel = guild.get_channel(699577970117050399)
messages = await channel.history(limit=None).flatten()
for i in messages:
with open("stuff.txt", "w") as wf:
wf.write(i.attachments)```i am using 2.0
It got changed
Itβs now [message async for message in channel.history(β¦)]
List comprehension
How to make the warns on other servers different, otherwise it issued a varn on one server, and it is shown on all?
Sql
ah that i hadnt seen in the changelog
Help me pls
wzr youve been asking that for a bunch of days now right, i sent you an answer in #databases some time earlier
A
should i do if (msg.author.id) or
#databases message
can you be more specific about what part you're stuck on?
didn't see it, sorry
@verbal breach depends on what you named the variable/parameter storing the Message object
I'm stuck on the fact that I can't make server warns, I have them on all servers the same
though whatever it is the parentheses in that if-statement isn't necessary
π€
how can i only print the message attachments?
async def on_message(ctx):
if (message.author.id == dont know what to put here):
#βexampleβ
is this correct
on_message doesnt accept ctx
@hushed galleon help me pls
well i already suggested rewriting your table to use a compound primary key, what issues are you having with that
@client.event
async def on_message(message):
if (message.author.id == dont know what to put here):
print(ctx.author.id)
hello i need help
how about this
in self bot code
that would be correct
ctx is undefined
Also no need for the brackets
aint javascript
I want it so that on_message. It sees if message.author.id == the authors id. It does something
wahhhh
T-T
just remove the parenthesis
ass
why
You don't need them
it doesnt effect it does it?
No but there's no reason to have it there
Why...?
if you're a beginner to programming you probably dont need to worry about style, whats more important are fundamentals like variables and functions
looks more organized
When you're beginning to program style is even more important.
Thats why im keeping it that way.
parenthesis*
i disagree, style is something you can learn later but you cant even begin to make programs without basic understanding of a procedural language
no brackets are [] and parenthesis are ()
people also distinguish them by saying square and round brackets
Depends where you are.
not really theyre mostly called by that
Yes really. You're free to Google it.
bro
async def on_message(message):
if (message.author.id == number):
print(author.id)
is this it
according to merriam webster "bracket" can be an alias for parentheses
author is undefined.
can i use something like author.content
No?
you cant make use of variables without declaring them beforehand
can anyone help?
what are you trying to do
you'd do !d content, but the docs cant guess what you mean by an arbitrary word "content"
as demonstrated
the docs are only there to tell you what different objects there are, what attributes those objects have, and sometimes offer examples of how they may be used, but they cant write the actual code you would use in your script
!write my code
pls
dam
you mean !e?
!e
code
!eval <code>
Can also use: e
*Run Python code and get the results.
This command supports multiple lines of code, including code wrapped inside a formatted code block. Code can be re-evaluated by editing the original message within 10 seconds and clicking the reaction that subsequently appears.
We've done our best to make this sandboxed, but do let us know if you manage to find an issue with it!*
!e my life decisions
@full lily :x: Your eval job has completed with return code 1.
001 | File "<string>", line 1
002 | my life decisions
003 | ^^^^
004 | SyntaxError: invalid syntax
ah
did your previous code fail with TypeError: string argument expected, got 'list'? or is your question not related to it anymore
!e if (message.author.id = num):
@verbal breach :x: Your eval job has completed with return code 1.
001 | File "<string>", line 1
002 | if (message.author.id = num):
003 | ^^^^^^^^^^^^^^^^^
004 | SyntaxError: cannot assign to attribute here. Maybe you meant '==' instead of '='?
bruh i forgor
no it just gives me a bunch of junk i dont need
!e if (message.author.id == id):
@verbal breach :x: Your eval job has completed with return code 1.
001 | File "<string>", line 1
002 | if (message.author.id == id):
003 | ^
004 | IndentationError: expected an indented block after 'if' statement on line 1
i only need the attachments
no
what specifically do you need from the attachment? the name of the file, or the contents of the file?
url
AHHHHHHHHGGGGGGGGG π‘π‘π‘π‘
!d discord.Attachment.url
The attachment URL. If the message this attachment was attached to is deleted, then this will 404.
print/write that url attribute
print(messages.attachments.url)this will give me an error cuz its a list
then you loop through the list and print the url for each attachment
Just loop over it
async def get_all_images(ctx):
guild = bot.get_guild(699577686795747349)
channel = guild.get_channel(699577970117050399)
messages = [messages.attachments.url async for messages in channel.history(limit=None)]
print(messages)``````
Ignoring exception in command get:
Traceback (most recent call last):
File "C:\Users\nikit\PycharmProjects\huhh\discord\ext\commands\core.py", line 186, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Users\nikit\PycharmProjects\huhh\docs\main.py", line 207, in get_all_images
messages = [messages.attachments.url async for messages in channel.history(limit=None)]
File "C:\Users\nikit\PycharmProjects\huhh\docs\main.py", line 207, in <listcomp>
messages = [messages.attachments.url async for messages in channel.history(limit=None)]
AttributeError: 'list' object has no attribute 'url'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\nikit\PycharmProjects\huhh\discord\ext\commands\bot.py", line 1183, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\nikit\PycharmProjects\huhh\discord\ext\commands\core.py", line 905, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
File "C:\Users\nikit\PycharmProjects\huhh\discord\ext\commands\core.py", line 195, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'list' object has no attribute 'url'```
message.attachments works btw
it just gives me everything
!resources < i would highly recommend some beginner guides on python before you start learning how to write a discord bot, because computers can't assume what you're trying to do from a few out-of-context words; its a programming language, so there's a structure to the code that is necessary for computers to understand what it means, and while you dont need to know everything to crush together programs that work, not knowing the fundamentals like variables and control structures will make it very difficult for you to understand what you're writing
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
anyone know?
.attachments is a list object
you're referencing message.attachments as you loop over message.attachments at the same time
!e
import discord
import os
import requests
import re
client = discord.Client()
@client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
@client.event
async def on_message(message):
if message.author == client.user:
return
if (message.author.id == "Gh0st#0726"):
await channel.message.send("hello, Gh0st.")
client.run(os.getenv('TOKEN'))
@verbal breach :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | ModuleNotFoundError: No module named 'discord'
bruh
thats not how eval works my guy
wahhhh
The userβs unique ID.
@verbal breach #bot-commands
well thats not descriptive... regardless the author id is an integer, so you wont be able to compare it to a user name
YESSSSSSS
first of all its message.channel.send and you are sorting by name
not the id
if you want a line by line explanation of an example bot there's one in the documentation's quickstart
https://discordpy.readthedocs.io/en/stable/quickstart.html
Traceback (most recent call last):
File "C:\Users\nikit\PycharmProjects\huhh\discord\ext\commands\core.py", line 186, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Users\nikit\PycharmProjects\huhh\docs\main.py", line 207, in get_all_images
messages = [messages.attachment async for messages in channel.history(limit=None)]
File "C:\Users\nikit\PycharmProjects\huhh\docs\main.py", line 207, in <listcomp>
messages = [messages.attachment async for messages in channel.history(limit=None)]
AttributeError: 'Message' object has no attribute 'attachment'```
it's attachments
message history gives you one list, and each of those gives you a list of attachments, so if you want a list of all attachments from all then you need a nested for-loop
!e
if (discord.User.id == "#0726"):
await channel.message.send("hello, Gh0st.")
@verbal breach :x: Your eval job has completed with return code 1.
001 | File "<string>", line 2
002 | SyntaxError: 'await' outside function
that gives me a list
oh
thatβs not an id
do you not know what a discord id is?
it is a discriminator
all_attachments = [
attachment
for message in history # code is simplified for this example
for attachment in message.attachments
]```
@verbal breach i suggest that before you start coding you learn the basics of Discord and of Python itself
!e
if (discord.User.id == "#0726"):
await message.channel.send("hello, Gh0st.")
@verbal breach :x: Your eval job has completed with return code 1.
001 | File "<string>", line 2
002 | SyntaxError: 'await' outside function
itβs not a user ID.
well discriminator is different from a user id, e.g. the python bot's discriminator is #4329 but their id is 409107086526644234
Let's keep the eval spam down please
The ling numbr right? Like
yes i know
oops mb i read it out of context
π
man i love modules installing fine on one device but failing on another
Docker π
Just don't screw up lol
?
Use docker
whatβs that?
Docker is a mini VM
ah
Common tool used in production. Isolates your code
You don't pollute your main system with programming languages, dependencies, random files
i mean yeah rn my plan is to just set up a VM
If you can get a program to work inside docker, it will work anywhere with minimal setup
you mean you shouldnt
Yes. That's why you use docker
mhm
So you don't have to install 20 different things and hope they all work on your system
Besides, docker is an important skill to know in the industry
Semi
or actually update pipπ
How to make <member 'id' of 'User' objects> print the actual id instead
a joke
!d discord.User.id ?
The userβs unique ID.
yes
!d discord.Member.id ?
property id```
Equivalent to [`User.id`](https://discordpy.readthedocs.io/en/master/api.html#discord.User.id "discord.User.id")
what do you mean by actual id
i was loading cogs on on_ready event this is probably bad getting rate limted and bot breaking while launching. how should i fix this ?
i want it to print the actual id instead of <member 'id' of 'User' objects>
stop copying me 
just load your cogs outside of on_ready
it doesnt ratelimit your bot? its just on_ready can trigger many times which would raise an error that the ext was already loaded
how do i make <member 'id' of 'User' objects> Print the 8384738374 as an example
if message.author != client.user:
await message.channel.send(discord.User.id)
right.
wouldn't it be message.author?
true
Simple oop. You use the id attribute of a discord.Member object. discord.Message.author returns a Member object.
hes not even calling the class which makes it even more funny since it would just send the obj loc
In an on_message event, message is your instance of the discord.Message class
ctrl z ?
cant lol
oh
the cache impl was so goodπ
what
from __future__ import annotations
from typing import Callable, Generic, Iterator, TypeVar
from typing_extensions import Self
from exceptions import DisabledCache
C = TypeVar("C")
class Cache(Generic[C]):
def __init__(self: Self, *, enabled: bool = False) -> None:
self.enabled = enabled
self.cache: dict[str, list[dict[str, str]]] = {}
def __len__(self: Self) -> int:
return len(self.cache)
def __iter__(self: Self) -> Iterator[str]:
return iter(self.cache)
def cancache(self: Self, m: Callable[..., C]) -> C | DisabledCache:
if self.enabled:
return m()
raise DisabledCache
@cancache
def save(self: Self, key: int, value: dict[str, list[dict[str, str]]], /) -> None:
self.cache[key] = value
it was so goodπ
what it do
I am trying to import a view from a file in my cog to my main.py file
just like any import?
yes
if its in a file it would be
from foldername.filename import classname
not working
show your file dir
Mm!
relative imports need a parent package
Ic
try it and it would raise an error
Ye i've tried it
yeah
It raise some "package" error
yeah
Why does that file have an emoji
from ticket_bot import myview
Task exception was never retrieved
future: <Task finished name='Task-1' coro=<SlashCommand.sync_all_commands() done, defined at /home/runner/Vora-Bot-v10/venv/lib/python3.8/site-packages/discord_slash/client.py:416> exception=HTTPException('400 Bad Request (error code: 50035): Invalid Form Body\nIn name: String value did not match validation regex.')>
Traceback (most recent call last):
File "/home/runner/Vora-Bot-v10/venv/lib/python3.8/site-packages/discord_slash/client.py", line 492, in sync_all_commands
raise ex
File "/home/runner/Vora-Bot-v10/venv/lib/python3.8/site-packages/discord_slash/client.py", line 472, in sync_all_commands
existing_cmds = await self.req.put_slash_commands(
File "/home/runner/Vora-Bot-v10/venv/lib/python3.8/site-packages/discord/http.py", line 254, in request
raise HTTPException(r, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In name: String value did not match validation regex.
I get this error when i start up bot what should i do?
why are you even using discord_slash
because, i want it to be easier to use commands, slash is easier anyways
So just use one of the forks?
bro main has slash commands?
disnakes impl is pretty easy
Whether or not he uses main or discord_slash right now the issue is that the command name doesn't match the regex required
True. You have an invalid slash command name
wait_for("button_click") 
how do i use the main discord slash instead of third party?
how do i find out which one doesnt match?
Since you're smart enough u deserve this nitro
Alr alr sorry dont use !otπ
lmaoo thats funny since my nitro is expiring π
πππ

Clicked on it tooπ i thought it was real
i didnt!
file icons
Like whats the point of that
"CHAT_INPUT command names and command option names must match the following regex ^[-_\p{L}\p{N}\p{sc=Deva}\p{sc=Thai}]{1,32}$ with the unicode flag set. If there is a lowercase variant of any letters used, you must use those. Characters with no lowercase variants and/or uncased letters are still allowed. USER and MESSAGE commands may be mixed case and can include spaces." (https://discord.com/developers/docs/interactions/application-commands#application-command-object)
Integrate your service with Discord β whether it's a bot or a game or whatever your wildest imagination can come up with.
im not taking offense to that necessarilyβ¦..i know the basics of python. I got really excited when i got start learning new things like the requests module,
I tried to do that and I couldnβt. Iβm not sure if itβs possible
do you even know what oop is?
πΏ
he didnt ment it as the expression oops
oopβ¦..
its a term which means Object Oriented Programming
I dropped a vase, object oriented programming, damn it
π
Waiting for reactive paradigm to get super popular
dont even know about it bro bless me with knowledge
To really simplify it, it's event driven programming
huh
Reactive, what an overloaded word. Many things turn out to become magically Reactive these days. In this post, we are going to talk about Reactive Programming, i.e. a development model structured around asynchronous data streams.
I know you are impatient to write your first reactive application, but before doing it, there are a couple of things...
Does anyone know how to make it where once you hit 20 the command stops working. Its pretty much a cap command max players on a team is 20 i wanna make it where once u hit 20 the command wont do anything.
Just spit balling but what happens if you do true, false, true, false
Yeah I'm out of ideas then
@bot.command()
async def my_command(...):
if condition:
return
# it's not 20
you can use while
Not really. It's not a loop
Having an issue where error states
discord.errors.ClientException: ffmpeg was not found.
FFmpeg is imported, with PyNaCl.
with youtube_dl.YoutubeDL(YDL_OPTIONS) as ydl:
info = ydl.extract_info(url, download=False)
url2 = info['formats'][0]['url']
voice_channel = ctx.author.voice.channel
source = await discord.FFmpegOpusAudio.from_probe(url2,**FFMPEG_OPTIONS)
vc.play(source)
We can't help with that, it's against Youtube's terms of service
Ah, they shut it down?
What, ffmpeg?
Yeah, I was watching tutorial on Youtube for a music bot
Makes sense. Don't get into the habit of watching youtube tutorials
lol
And streaming audio from youtube outside of youtube is in violation of their terms of service and is a surefire way to get your bot a cease and desist order
I'll see if I can subsitute youtube with spotify
Spotify doesn't allow it iirc
mann
Most platforms don't want you streaming music from them since they can't get the ad revenue
That's not to say there aren't any, it's just harder to find
Yeah I understand
One of the reason there's a shocking lack of music bots on discord these days
A solution for that is singing your own music and playing it
I have tried that once π
oh so anything that can reactively change
become a good artist and lend me your musicπ
if your address got leaked why are you leaking it again bro
and you should disconnect your router for about a day so your isp cycles ips or just contact them so they will change it
they will still know were you live but they cant ddos since your public ip was changed
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: module 'discord' has no attribute 'author'```
i keep getting this error
Let's see your code
the module doesnt have that attr
@bot.command()
async def suggest(ctx, *, message):
channel = bot.get_channel(958144429821132814)
author = ctx.author
await ctx.message.delete()
e=discord.Embed(title="Suggestion", description=message, color = discord.author.color)
e.set_footer(text=f"suggested by {ctx.author.name}#{ctx.author.discriminator} | β¬οΈ upvote | β¬οΈ downvote | β disapproved | β
next video | β already done")
e.set_author(name=ctx.message.author, url=ctx.author.avatar_url)
message = await ctx.send(embed=e)
Never could've guessed that myself from that error. Genius
you should give me that helper role since im such a Genius
There, discord.author
Should be ctx.author
Also instead of doing f"{ctx.author.name}#{ctx.author.discriminator}", you can just do f"{ctx.author}"
oh i wasn't paying attention,
. i think my autocomplete thing took over
Yes. Usually the errors are pretty descriptive
but only smort people like me can know the real issue
not even a helper 
how can I mention a member
member.mention
Command raised an exception: AttributeError: 'Member' object has no attribute 'username'
Yes. It's .mention
I am using that
The error says otherwise
and you could just use or so no need for the if statement
member = member or ctx.author
Again, I can't reiterate the fact that errors in python are VERY clear and they can lead you to the exact source of the error if you know how to read them
Read the error. It tells you the exact line and what the problem is
Just as the code said
"Member has no attribute username"
message.author returns a member object!
see?
which the attr isnt even needed as Context already has the author attr!
aw it deletes it
i feel like when the docs arent found it shouldnt be deleted tbh
I confused myself
RS = 21
`{len([member for member in role.members])}/{RS}`
if {len([member for member in role.members])} > {RS}:
await ctx.send(f"test")```
im trying to make it where once the role.members hits the RS (21) then it sends "test"
why are you iterating role.members to make it a list if it already returns a list?
it doesnt return a list
!d discord.Role.members
property members```
Returns all the members with this role.
role.members does return a list
weird
it does this
!e ```py
import difflib
class Example:
def init(self) -> None:
self.bar = "bar"
self.baz = "baz"
def __getattr__(self, attribute: str) -> "Any":
try:
return super().__getattribute__(attribute)
except AttributeError:
close = difflib.get_close_matches(attribute, self.__dict__)
raise AttributeError(f"{self.__class__!r} object has no attribute `{attribute}`. Did you mean `{close}`")
Example().bar
Example().baz
Example().bat
@pliant gulch :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 11, in __getattr__
003 | AttributeError: 'Example' object has no attribute 'bat'
004 |
005 | During handling of the above exception, another exception occurred:
006 |
007 | Traceback (most recent call last):
008 | File "<string>", line 18, in <module>
009 | File "<string>", line 14, in __getattr__
010 | AttributeError: <class '__main__.Example'> object has no attribute `bat`. Did you mean `['baz', 'bar']`. Did you mean: 'bar'?
Imagine if discord.py did this
its because he's using a for loop
Would just add overhead. But would be a nice feature nonetheless
i just said weird as he said it didnt return a list when it actually does lmfao
that would be sick
yes but did he print it is the question 
should be done
ok
Mm def not a serious suggestion, but a lot of people don't see to know what attribute errors are
why would he
mostly when the attr returns another object and they get an attr error
so see if its a list 
wat da faq is a attr
attribute
~~so whats an attribute
~~
disnake/role.py lines 361 to 369
@property
def members(self) -> List[Member]:
"""List[:class:`βMember`β]: Returns all the members with this role."""
all_members = self.guild.members
if self.is_default():
return all_members
role_id = self.id
return [member for member in all_members if member._roles.has(role_id)]```
ok jeez
how to make something like @commands.has_perms
is is like @bot.check
to check what exactly?
like specific people instead of writing an if statement each command
so a whitelist? and yes it would be the check deco of the Bot class
so py @bot.check async def is_specific_owner(): return "yes"
Something like that?
!d discord.ext.commands.Bot.check
@check```
A decorator that adds a global check to the bot.
A global check is similar to a [`check()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that is applied on a per command basis except it is run before any command checks have been verified and applies to every command the bot has.
Note
This function can either be a regular function or a coroutine.
Similar to a command [`check()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check"), this takes a single parameter of type [`Context`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Context "discord.ext.commands.Context") and can only raise exceptions inherited from [`CommandError`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CommandError "discord.ext.commands.CommandError").
Example...
This function can either be a regular function or a coroutine.
oh so just @check() ok and to call it is it just @commands.checkname() ?
You need to specifiy in your function signature that it takes Context
theres examples in docs!
Ez ok lemme check it out
@slate swan is it ctx.message.author.name
Huh pretty simple
for the name of the author yes but no need for the message attr
Context already has the attr
!d discord.ext.commands.Context.author
Union[User, Member]: Returns the author associated with this contextβs command. Shorthand for Message.author
so it could just me message.author.name
no
ctx.author.name
I typed it wrong mb
I meant that yeah
how couldve you typed a whole phrase wrong
when I run the command it isn't saying the correct key value for my json file though
just index the key correctly for the right value
I have it like this
{"y9su#8009": 1}
but it's saying I have 0 points
ctx.author.name doesn't include the discriminator
do discord bots in pythons still work?
Either way, I would suggest storing the USER ID, not the username and discriminator.
well you dont have points and you shouldnt use tags anyways
They can change names, etc. While IDs cannot
getting ratelimted pop on terminal after launching bot WARNING:discord.gateway:WebSocket in shard ID 0 is ratelimited, waiting 58.99 seconds tho bot's working fine, able to use command while ratelimited. i guess bot does not when its get rate limited. this WARNING pop up every minute.
i dont know whats wrongπ
if I use ID's how would I be able to ping for a user to check there points
<@id>
Ahh
yes why wouldnt they?
or {ctx.author.mention} (in f strring)
mine completely broke for some reason a few weeks ago
why even assume such a thing lmfao
it logs on fine but it doesnt pick up any messages and sends nothing
does ctx.message.author.name include disciminator? if not what does
you probably have 2 on message events
sounds like an intents issue
making the member obj a string already shows the whole tag
like having multipe if in message. contain?
so that line isnt my problem
what
since the message content intent is a thing, and that's what gives you the content of a message (as well as attachments and what not)
ctx.message.author.name shows username and tag yes
no
it doesnt
what does it show
bro
it literally says it your discord name!
Cast the user object to str to get user#tag or name + discriminator
property name```
Equivalent to [`User.name`](https://discordpy.readthedocs.io/en/master/api.html#discord.User.name "discord.User.name")
bro no
only the username and not the discriminator
Ok then, what shows both?
^
so the await bot.process_commands(message) would go on the same indent outside of the brackets?
!d discord.ext.commands.Bot.listen
@listen(name=None)```
A decorator that registers another function as an external event listener. Basically this allows you to listen to multiple events from different places e.g. such as [`on_ready()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_ready "discord.on_ready")
The functions being listened to must be a [coroutine](https://docs.python.org/3/library/asyncio-task.html#coroutine "(in Python v3.10)").
Example...
just use this deco
https://github.com/Rapptz/discord.py/blob/master/discord/member.py#L361-L362 well would you look at that the Member class's string dunder 
discord/member.py lines 361 to 362
def __str__(self) -> str:
return str(self._user)```
what do you mean
bro
im on to many drugs for this I swear π
so its basicaly the bot seeing multiple events at once?

@slate swan the class has the string dunder which if the class gets casted to a string it would return the value of the string dunder
what the fuck is dunder
bro
__str__ __init__etc are dunders or special methods
i mean you could say that
its saying that bot isin't defined
well its not defined?
not a problem
ctx.author.discriminator gets only the tag right
yes
!d discord.Member.discriminator
property discriminator```
Equivalent to [`User.discriminator`](https://discordpy.readthedocs.io/en/master/api.html#discord.User.discriminator "discord.User.discriminator")
so if I use both it would get both?
bro
ctx.message.author.name + ctx.message.author.discriminator
yes but you already been told casting the obj into a string already returns both?
please stop calling me bro, my pronouns are xe,xey,xem
what what would it be defined as user?
are you joking? or being serious.
why would I joke about pronouns.
pardon?
trolls are a thing
disrespectful
i feel like im doing something wrong
how........
not you, the trolls are
ah yeah
the messages are under a client event, which are the events I'm trying to fix
not sure what you mean or is your problem
rewrite this with smaller words (easier to understand)
when i type a command, nothing happens, and no error is displayed
use str()
ok ok str(obj) converts a object/class into a string which the string dunder/special method is responsible to return a value when the class is casted into a string which since your obj and attrs are in a f string no need to so just add the Context class and the author attr ( ctx.author ) which it would just cast the Member obj since the author attr returns a Member obj into a string which i earlier showed the string dunder/special method of the member class.
lmao hope he understands
???
lmao knew it

the first one okimii said was more simplier
I go by xe/xem/xey.
tl;dr use str()
pls learn oop and basic pythonπ
no need its in an f string so its already being casted as a string
oh it is?
yeah in xey code
should of read more

