#discord-bots
1 messages ยท Page 35 of 1
@discord.ui.button(label="Rock", style=discord.ButtonStyle.green, emoji="๐ชจ")
async def rock_callback(self, interaction, _button):
if not self.interaction.user in self.players:```
AttributeError: 'RPS' object has no attribute 'interaction'```
just interaction
oh okay
Got it
AttributeError: 'Button' object has no attribute 'user'```
What's the interaction.user called
interaction.member?
change _button and interaction places
Ohh
i forgot
this fixed it and it worked!!
Tysm, now i'll work on completing the entire code of the command- the core is now complete!
congrats
@discord.ui.button(label="Rock", style=discord.ButtonStyle.green, emoji="๐ชจ")
async def rock_callback(self, _button, interaction):
if not interaction.user in self.players:
return await interaction.response.send_message(ephemeral=True, embed=discord.Embed(description=f":x: This isn't your interaction menu.", colour=discord.Colour(error(self.ctx.guild.id))))
if interaction.user == self.ctx.author:
if self.answer_1 == "":
self.answer_1 = "rock"
return await interaction.response.send_message(ephemeral=True, embed=discord.Embed(description=f":AdvancedBotTick: You selected `rock`.", colour=discord.Colour(success(self.ctx.guild.id))))
if not self.answer_1 == "" and self.answer_2 == "":
rock_callback.disable
else:
return await interaction.response.send_message(ephemeral=True, embed=discord.Embed(description=f":x: You already selected `{self.answer_1}`.", colour=discord.Colour(error(self.ctx.guild.id))))```
how do i disable a button?
i tried doing rock_callback.disable
nope
well so to disable a button you need to edit a whole message and change view
almost
View has children attr, which returns list of buttons the view has, well not only buttons, select menus and etc
so you do self.children[0].disabled = True
oh
and then await message.edit(embed=embed, view=self)
nope
this in the class itself? message would be defined?
Or the command
no
oh wait i think i understood
message_contant instance is imp for cogs and on_message right ?
if not view.answer_1 == "" and view.answer_2 == "":
await message.edit(embed=embed, view=self)```
and before that line message = await ctx.send(my embed here)
And this will be in my rps command right
where do you want the button to disable?
wait self might not be defined there
@limber bison stop spamming commands
!d discord.Intents
class discord.Intents(value=0, **kwargs)```
Wraps up a Discord gateway intent flag.
Similar to [`Permissions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions "discord.Permissions"), the properties provided are two way. You can set and retrieve individual bits using the properties as if they were regular bools.
To construct an object you can pass keyword arguments denoting the flags to enable or disable.
This is used to disable certain gateway features that are unnecessary to run your bot. To make use of this, it is passed to the `intents` keyword argument of [`Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client").
New in version 1.5.
basically when both parties select an answer, i want it to disable all buttons
๐ฎ
interaction.message would be the message right (the embed here)
what message
the first embed in the picture
oh wait yes, i forgot that there is an attr in interaction, well it's actually called different
oh no there isn't
im still extra dumb
its original_response
which will return your ephemeral message
which noone needs
code of conduct
?
!d discord.View.on_timeout
discord.ui.View
also on_timeout is on timeout
Cheeeeers
not on both players done
i got it working
msg is ctx.channel.fetch_message(interaction.message.id)
Now it disables all buttons :) once both parties select a button
nooo(
?
view.message = await ctx.send(embed=..., view=view)
and then in callback self.message
oh
my code gives the same output but logic wise but yours is more efficient to do the same
@bot.command()
async def tempmute(ctx, member: discord.Member, time=0, reason=None):
if not member or time == 0:
return
elif reason == None:
reason = 'no reason provided'
try:
if time[2] == "s":
time_in_s = int(time[1])
if time[2] == "min":
time_in_s = int(time[1]) * 60
if time[2] == "h":
time_in_s = int(time[1]) * 60 * 60
if time[2] == "d":
time_in_s = int(time[1]) * 60 * 60 * 60
except:
time_in_s = 0
await ctx.channel.purge(limit=1)
await ctx.send("ok")
await member.timeout(time_in_s)
await asyncio.sleep(time_in_s)
await ctx.send("done")
return
Error
Traceback (most recent call last):
File "D:\New folder\pythonProject\venv\lib\site-packages\discord\ext\commands\core.py", line 200, in wrapped
ret = await coro(*args, **kwargs)
File "D:\New folder\pythonProject\main.py", line 52, in tempmute
await member.timeout(time_in_s)
File "D:\New folder\pythonProject\venv\lib\site-packages\discord\member.py", line 971, in timeout
raise TypeError(f'expected None, datetime.datetime, or datetime.timedelta not {until.__class__!r}')
TypeError: expected None, datetime.datetime, or datetime.timedelta not <class 'int'>
The above exception was the direct cause of the following exception:```
read the error
you need to pass a datetime or timedelta, not an int
how do i pass datetime ?
class datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)```
All arguments are optional and default to `0`. Arguments may be integers or floats, and may be positive or negative.
Only *days*, *seconds* and *microseconds* are stored internally. Arguments are converted to those units...
How ??
I havent ever used datetime module as such...got 00 info sry
did u even look at the docs?
there is literally an example
of how to create a timdelta instance
yes i read them but idk how to add them in my code
What is instance ?
timedelta(seconds=time_in_s) is this that hard to figure out?
Valued object
class Mama: # this is class
pass
yes = Mama() # this is an instance of class Mama
no = Mama() # this is also an instance of class Mama```
Ohk k
sryy
@bot.command()
async def tempmute(ctx, member: discord.Member, time=0, reason=None):
delta = timedelta(
days=50,
seconds=27,
microseconds=10,
milliseconds=29000,
minutes=5,
hours=8,
weeks=2
)
if not member or time == 0:
return
elif reason == None:
reason = 'no reason provided'
try:
if time[2] == "s":
time_in_s = int(time[1])
if time[2] == "min":
time_in_s = int(time[1]) * 60
if time[2] == "h":
time_in_s = int(time[1]) * 60 * 60
if time[2] == "d":
time_in_s = int(time[1]) * 60 * 60 * 60
except:
time_in_s = 0
await ctx.channel.purge(limit=1)
await ctx.send("ok")
await member.timeout(timedelta(seconds=time_in_s))
await asyncio.sleep(timedelta(seconds=time_in_s))
await ctx.send("done")
return
so like this right ?
noway....
Professional copypaster
how can people be that... not smart
Similar to objects in other languages ๐ณ like java and c++
Right ?
Also do this for time conversion #discord-bots message
Instance and object are synonymous
you know programming langs are pretty similar, just diff syntax
You can call instance an object and vise versa
this is so weird
Ohh k k got it bosss
My client is instance of discord.Bot class
Hahahahaha
Nothing weird just regex
just look at this https://github.com/Rapptz/RoboDanny/blob/rewrite/cogs/utils/time.py, so smooth and nice
๐ค
That regex too long
Mine is too
no yours is weird
Your problem
what is d4h2
no ๐ญ mf ๐ญ im hiding from my parents, and just came online to see this answer by them ๐ญ so im not putting all my mind into it
There's no such thing
until tomorrow at 3 PM isnt this just so smooth?
well 
This is NLP
wohcraes
wohcraes
!pypi durations-nlp
Imagine not creating time conversion from scratch
that's available new keyword after aysnc (aysnc wohcraes)
both do the same work
thats on pypi
just pip install
๐ณ
๐ฟ
i thought there is no such smooth thing as https://github.com/Rapptz/RoboDanny/blob/rewrite/cogs/utils/time.py in the internet world
where Michael Jackson
smooth criminal ;-;
wdym message counter
like this
i had an old code from 2020 which did count messages in a json file which has worked till now with no issues (this bot is in only one dead server)
but the thing is for a large scale bot it wont work properly, i need a better database
every time someone sends a message it appends their msg count in a database
is there any work around for adding callback to an url button?
Like if he clicks the button, he'll activate a function and then be redirected
well... the best DB imo and probably very recommended for dpy bots is PostgreSQL, however the easiest one, which I think can handle message counts is sqlite3
no
duck
Thanks
impossible
Guys how to fix this error
@bot.command()
async def leaderboard(ctx):
leader = []
conn = bot.db
cur = await conn.cursor()
for i in cur.execute("""SELECT user, points FROM leaderboard ORDER BY points DESC"""):
leader.append(str(i).replace(",", str("|")+str(" ")+str("|" )))
leaderV = "\n".join(leader)
await ctx.reply(f"~ ๐ค**[Player]**๐ค ๐ฏ**[Score]**๐ฏ ~\n **-----------------------------------------------------------------------------** ```{str(leaderV)}```")
Here is my code
Tupple?
not sure what db you use so can tell how
no, the Cursor obj
Sqlite
then it's await cursor.fetchall()
Where do I add it?
btw you can do this to make it shorter ```py
cur = await conn.execute("""SELECT user, points FROM leaderboard ORDER BY points DESC""")
rows = await cur.fetchall()
for i in rows:```
Oh k
Ty for help
np
Me?
yes you
oh whoevers it is if theyre using it to host then alert them ๐
No i meant
everyone has a shared ip
and if youre not using an env variable and directly use token in your code then your token is public
yeah
anyone can use your token and hence the bot to do anything they want
basically abusing permissions the bot has in any server
- anyone else abusing the service on repl.it and gets ratelimited, your bot gets ratelimited as well because of shared ip
yeah btw I forgot that sqlite3 is not async so aiosqlite is better, but for beginning it doesnt really matter. I used sqlite3 for more then a year
here for detailed #965291480992321536 message
oh
aiosqlite is a server db?
and sqlite is local?
its async
its not even a host
no aiosqlite is an async wrapper around sqlite
postgre is a server db
mysql :)
sigh
Do we need to buy server for postgre?
depends
Rent?
on your host
Sqlite is better then
Hey! How can i make it so only the people with permissions with Administrator can see this? And also the guy who created the ticket?
!d discord.Guild.create_text_channel
await create_text_channel(name, *, reason=None, category=None, news=False, position=..., topic=..., slowmode_delay=..., nsfw=..., overwrites=..., default_auto_archive_duration=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Creates a [`TextChannel`](https://discordpy.readthedocs.io/en/latest/api.html#discord.TextChannel "discord.TextChannel") for the guild.
Note that you need the [`manage_channels`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_channels "discord.Permissions.manage_channels") permission to create the channel.
The `overwrites` parameter can be used to create a โsecretโ channel upon creation. This parameter expects a [`dict`](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.10)") of overwrites with the target (either a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member") or a [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role")) as the key and a [`PermissionOverwrite`](https://discordpy.readthedocs.io/en/latest/api.html#discord.PermissionOverwrite "discord.PermissionOverwrite") as the value.
Note
Creating a channel of a specified position will not update the position of other channels to follow suit. A follow-up call to [`edit()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.TextChannel.edit "discord.TextChannel.edit") will be required to update the position of the channel in the channel list...
Channel permissions:
Role/member| Granted permissions |
-----------+-----------------------------------------------------+
everyone | View Channel = False |
member | View Channel = True |
admin_role | View Channel = True |
btw people with admin perms should see the channel anyway
iirc
how do you do that so fast
Anyone else get frustrated that 99% of people don't use half of the features of your bot, usually the stuff that you think is the most fun and took the longest to code 
!pypi tabulate
The thing I can think of
yeah
Yeah
Must be a way to structure things to make people use it but want to 
no i just wrote it on my own
like | this |
-----+------+
yes | True |
no | False|```
Gigachad
โ๏ธ
how can i make it so if the user presses a button it sends a message?
await callback(interaction)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
The callback associated with this UI item.
This can be overridden by subclasses.
True 
I relate to u
How can i edit the message above to remove the right button when it was used? And how can i make it that only Admins can use it?
No
PostgreSQL is free to setup
how to get all permission overrides in a channel
channel.permissions? whats it called
!d discord.TextChannel.overwrites
property overwrites```
Returns all of the channelโs overwrites.
This is returned as a dictionary where the key contains the target which can be either a [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role") or a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member") and the value is the overwrite as a [`PermissionOverwrite`](https://discordpy.readthedocs.io/en/latest/api.html#discord.PermissionOverwrite "discord.PermissionOverwrite").
Changed in version 2.0: Overwrites can now be type-aware [`Object`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Object "discord.Object") in case of cache lookup failure
interaction.response.send_message
thanks but i already got it
!d discord.InteractionResponse.send_message
await send_message(content=None, *, embed=..., embeds=..., file=..., files=..., view=..., tts=False, ephemeral=False, allowed_mentions=..., suppress_embeds=False)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Responds to this interaction by sending a message.
not that easy(
oh
!d discord.Guild.emoji_limit
property emoji_limit```
The maximum number of emoji slots this guild has.
!d discord.Guild.create_sticker
await create_sticker(*, name, description, emoji, file, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Creates a [`Sticker`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Sticker "discord.Sticker") for the guild.
You must have [`manage_emojis_and_stickers`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_emojis_and_stickers "discord.Permissions.manage_emojis_and_stickers") permission to do this.
New in version 2.0.
Thanks
how can i disable a button after i click on it?
!d discord.Button.disabled
Whether the button is disabled or not.
get this button in the view, set disabled to True and do message.edit(view=updated_view)
you can get the button via view.children for example
How would I get the server ip and port then?
do you know how servers work?
How to get a user?
by id, or?
await client.fetch_user(id)?
!d discord.ext.commands.Bot.get_user
get_user(id, /)```
Returns a user with the given ID.
Changed in version 2.0: `id` parameter is now positional-only.
^ that
this also
k ty
you host the postgres server on your machine, and when connecting to it you'd usually use 127.0.0.1 with port 5432 (default)
localhost ๐
b- but 127.0.0.1 hacker mode
Not much
So can I dm them by doing this?
user = await bot.fetch_user(id)
await user.send(โ. . . โ)
```?
Guys, how do I add description to each parameter of my slash commands?
yes
k ty
discordpy?
disnake but they should be the same
not really
howd u do it in discord.py?
slash command implementations differ between forks
@app_commands.describe decorator
Sorry @silk fulcrum but I'm very confused, because the text I need to edit the buttons from is in another class, i dont know if i didnt understood u but i created another class with the buttons and disabled the one, but now i cant edit the embed... Sorry if its explained poorly
tysm
works perfectly ty
Guys like we can make a comand to run python code in dpy . Is there way to make a comand that can run js code?
๐ณ why would you need that
well technically it's possible, you just need js code interpreter and... idk... but it's 1000000 times harder than opening ide
it wont be just copy + paste
Any library to do that?
idk, googleit
disnake.ext.commands.errors.CommandInvokeError: Command raised an exception: InteractionTimedOut: Interaction took more than 3 seconds to be responded to. Please defer it using "interaction.response.defer" on the start of your command. Later you may send a response by editing the deferred message using "interaction.edit_original_message"
Note: This might also be caused by a misconfiguration in the components make sure you do not respond twice in case this is a component.
that's just... really weird idea
Why is it giving me this error even though im responding within 3 seconds
just defer it
idk how disnake works, ig it's okay, just defer it
nice
!pypi js2py
So a basic python question here, but how to get the guild with most members?
iterate over your guilds, sort by members, get first item, ez
Did this with this
Hey so in the future is discord making it so that you can only user slash commands?
Your bot can't have your old regular message commands and then add on new commands as slash commands?
no, that is only for verified bots
unverified bots are not affected
how do I create a button that when clicked the bot respond?
!d discord.Button.callback
!d discord.ui.Button.callback
await callback(interaction)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
The callback associated with this UI item.
This can be overridden by subclasses.
Good idea. I can use list.sort and add a condition
@green wraith no, wait look at example better: https://github.com/Rapptz/discord.py/blob/master/examples/views/confirm.py
thanks friend ๐
it'll help more than this page in docs
max(bot.guilds, key=lambda x: x.member_count)```
It's easier than it seems
dont reveal secrets
Just sharing knowledge
Just joking
list(sorted(bot.guilds, key=lambda i: len(i.members), reversed=True))[0]
yeah max better here
Sorting is expensive
hi guys how can i retrieve the date a discord account was created when they join my server
!d discord.Member.created_at -- created date
property created_at```
Equivalent to [`User.created_at`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User.created_at "discord.User.created_at")
thanks
!d discord.Member.joined_at -- joined server date
An aware datetime object that specifies the date and time in UTC that the member joined the guild. If the member left and rejoined the guild, this will be the latest date. In certain cases, this can be None.
only needed the top one but appreciate it
ok
32 flexing ๐
ah so basically just want to check that there account is over 30 days old when joining my server
lmfao i was just jk
if that makes sense
you were just jk?
Asher is joke
๐
I still need help disabling a button after it got used
hope someone can help more than google and stack overflow
channek
just do disabled=True
typo
that's not all
But then the button cant even be used ever
๐ณ
also if Google and stack cannot help you that's skill issue from your side :kek:
isnt that what you want?
no
well they're pretty bad with dpy
then do disabled=False
I want to disable the button only after it got pressed
discord does that
till the response is processed
the buttons infact all other buttons are disabled
temporarily
๐ I mean i want to make the button unusable after it got used, because now i can press it so often i want
your ticket will be handled by darek 2
import sys, subprocess, random, json, asyncio, os, time try: import colorama, pyfade, discord except ImportError: subprocess.check_call([sys.executable, "-m", "pip", "install", 'colorama']) subprocess.check_call([sys.executable, "-m", "pip", "install", 'pyfade']) subprocess.check_call([sys.executable, "-m", "pip", "install", 'discord.py']) subprocess.check_call([sys.executable, "-m", "pip", "install", 'discord']) from colorama import Fore from datetime import datetime from discord.ext import commands def error_msg(): print(pyfade.Fade.Horizontal(pyfade.Colors.purple_to_red, """Bruhhhh\nSeems like you\'re new to Python and/or JSON..\nJoin the Support-Server and lemme help you :)\n""")) time.sleep(10) input(f"{Fore.YELLOW}Press Enter to exit the script") raise SystemExit sys.tracebacklimit = 0 bot = discord.Client() with open("tokens.json", "r") as file: tokens = json.load(file) with open("alrdyusedtokens.json", "r") as file: tokenscheck = json.load(file)
AttributeError: module 'discord' has no attribute 'Client'
bot = Client ๐ญ
help
Doesn't look right, did you name a file "discord.py"
Nope
something's definitely overwriting discord
are there any other files in your project?
Yes i have already fixed
sorry
that seems like a very unlikely situation @silk fulcrum
I thought you were responding to Iorran
ah ic
You haven't installed discord.py 2.0
To install it, pip install git+https://github.com/Rapptz/discord.py
sorry, but I did not understand what and to do.
my brain goes off when I'm eating a pie + making minesweeper command + helping people
okay
mooltitask
f*ck
If i change button lable at High speed will it rate limite ?
how Do I create a Slash Commands?
Hello, I'm coding a bot in python, I have a little problem, I'm coding a system that allows me to see if the user is in voice in my server, but it gives me this error
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'voice'
Can you help me?
my SlashClient was not recognized
@silk fulcrum
update dpy
pip***<python version>*** install -U git+https://github.com/Rapptz/discord.py
can't delete the embed on my phone
ctx.voice_clients,``` this was deprecated to what ?
I wanted to do a command in slash using main.py
@limber bison :white_check_mark: Your 3.11 eval job has completed with return code 0.
0
it was never deprecated
!d discord.ext.commands.Context.voice_client
property voice_client```
A shortcut to [`Guild.voice_client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild.voice_client "discord.Guild.voice_client"), if applicable.
TIL key exists in max too
does anyone have cogs with subdirectory?
Yo, is it possible to add a field at a specific row?
I don't think so from looking through the docs, but maybe i'm wrong
I am trying to make a currency bot in discord.py. I made it that it will store add 5 cookies everytime the user messages.
Now how can I make a jar command to check how many cookies does a user have?
here is my code
import discord
from discord.ext import commands
import json
bot = commands.Bot(command_prefix='> ', intents=discord.Intents.all())
@bot.event
async def on_ready():
print("Bot is Now Online")
@bot.event
async def on_message(message):
user_id = str(message.author.id)
with open("jar.json", "r") as file:
jar = json.load(file)
if not user_id in jar:
jar[user_id] = {}
jar[user_id]["cookies"] = 0
[user_id]["cookies"] += 5
with open("jar.json", "w") as file:
json.dump(jar, file)
await bot.process_commands(message)
@bot.command()
async def jar(ctx):
user_id = str(ctx.author.id)
with open("jar.json", "r") as f:
jar=json.load(f)
cookie_amt=jar[user_id]["cookies"]
await ctx.author.send(f"You have {cookie_amt} cookies in your jar.")
bot.run(token)
File "C:\Users\8ster\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 466, in _run_event
await coro(*args, **kwargs)
File "c:\Users\8ster\Desktop\projects\Discord Bots\Novicookies\main.py", line 24, in on_message
[user_id]["cookies"] += 5
TypeError: list indices must be integers or slices, not str```
How do I count on how many servers my bot is on?
I think you need to put jar in front of [user_id]["cookies"] += 5
right now it thinks user_id is just a list
do
await message.channel.send(f"{str(len(client.guilds))}")
Does
button.label = values interaction.response.edit_message(view=self)
Has rate limit ?
len(bot.guilds)
thanks
Editing does as it is API call
And yeah it needs to be awaited
I have the following problem: I installed discord.py v 2 using pip install -U git+https://github.com/Rapptz/discord.py, but the code:
from discord.ext import commands, tasks
import discord
bot = commands.Bot()
@bot.slash_command(guild_ids=[id])
async def test(ctx):
ctx.send("Test")
bot.run(token)
``` doesnt work... Can anybody help?My traceback is:
Traceback (most recent call last):
File "C:\Users\Admin\PycharmProjects\Snap\Final2\main-slash.py", line 28, in <module>
bot = commands.Bot()
TypeError: init() missing 1 required positional argument: 'command_prefix'
you need to give the bot a command prefix
bot = commands.Bot('!')
Traceback (most recent call last):
File "C:\Users\Admin\PycharmProjects\Snap\Final2\main-slash.py", line 473, in <module>
@bot.slash_command(guild_ids=[cfg["guild_id"]])
AttributeError: 'Bot' object has no attribute 'slash_command'
@slash_command(*args, **kwargs)```
A shortcut decorator that invokes [`slash_command()`](https://docs.disnake.dev/en/latest/ext/commands/api.html#disnake.ext.commands.slash_command "disnake.ext.commands.slash_command") and adds it to the internal command list.
disnake does though
hm okay
Dpy still has that ๐ง
i want to dm a person that i warn but it dms me
how can i do this?
@bot.command(pass_context=True)
async def warn(ctx, user: discord.Member, role: discord.Role, why):
guild = ctx.guild
channel = guild.get_channel(1008388083508576367)
await user.add_roles(role)
await ctx.send(str(user) + " you have been warned for " + str(why))
await channel.send(str(user) + " has been warned for " + str(why))
await ctx.author.send("you have been warned for " + str(why))
you need to do
await user.send('this is a DM message')
ok
!d discord.Member.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**.
also name your user var as member isntead
thx it worked
???
If i edit button label at rate 100/sec will it able to hendil ?
Im trying to grab questions from a .txt file everytime the user puts the command ?wyr. I tried using this code but it was not working? Could someone help me please @bot.command() async def wyr(ctx): with open ('wyr.txt'): await ctx.send(random.choice(wyr.txt()))
and command count, how is it?
Ratelimit is 50/sec
dude my bot can hit edits cleaner than me
?
fortnite
Amogus
sussy baka
Where didi u read this ? ๐ณ
This is incorrect file reading. Correct one looks like this
@bot.command()
async def wyr(ctx):
with open("wyr.txt", "r") as f:
await ctx.send(f.readlines())```
Integrate your service with Discord โ whether it's a bot or a game or whatever your wildest imagination can come up with.
I need help pls
what is the equal command of seeing the total servers only in the commands?
Man what I showed to you is useable everywhere
@vale wing can u help me?
where?
What's this mean ?
len(bot.guilds)
Is interaction have more rate limit ?
WHATTTT
Eh lemme check rq
Most likely it means they have different ratelimit
What's that, i think they didn't mention ๐ณ
Lol
Not sure what you mean
@slash.slash(name="google", description="Search on google")
async def google(ctx, *, search):
link = f"https:/letmegooglethat.com/?q={search}"
await ctx.send(link)```
how to put several words ?
"+".join(search.split())
Idk what that thing accepts tho
It might be URL encoded
link = f"https:/letmegooglethat.com/?q={search}" "+".join(search.split())
like this?
!d urllib.parse.quote_plus use this
urllib.parse.quote_plus(string, safe='', encoding=None, errors=None)```
Like [`quote()`](https://docs.python.org/3/library/urllib.parse.html#urllib.parse.quote "urllib.parse.quote"), but also replace spaces with plus signs, as required for quoting HTML form values when building up a query string to go into a URL. Plus signs in the original string are escaped unless they are included in *safe*. It also does not have *safe* default to `'/'`.
Example: `quote_plus('/El Niรฑo/')` yields `'%2FEl+Ni%C3%B1o%2F'`.
I just want to be able to search from my order
How can i make a counter for giveaway system?
User your database query!
I dont even use db wdym?
Insert interaction entrys and then count them !
Which db u use ?
They donโt use a database
Idk startup cmd to start the bot
In your code or starting the script?
Is buttons with edit label on every click is good idea ?
๐
Like count reaction
Thank you it works :D. But the bot sends all the lines within the .txt file and I want it to randomly choose one of the questions within the .txt instead
Then just put choice
How are you gonna start the bot without the bot running lol
For this case it's better to write count to some variable and periodically update the label, if too many people press it suddenly you are going to get ratelimited
If count%20 == 0
Update
??? This will be good ?
Won't get ratelimited if it's component based though
(interaction based)
Wot about this ?
Not really I think, the edit message endpoint is not interaction based https://discord.com/developers/docs/resources/channel#edit-message
Integrate your service with Discord โ whether it's a bot or a game or whatever your wildest imagination can come up with.
Nah that's a different endpoint altogether
How tho
Check in the Interaction responses section, you'll find the UPDATE_MESSAGE type
I don't see where to put it
Interaction.response.edit_message doesn't use that endpoint
Dose it have rate limit then ?
for some reason discord doesn't tell what they are exactly
Discord will give an interaction for each click
Conclusion lol ????
how to get discord api ping?
how do I create an economy command?
bot.letency ๐ค
It's fine if you use ui components and edit the message with InteractionResponse.edit_message
it is for the bot's latency
New ?
If you use the normal Message.edit ep you can get ratelimited
Ohhh k k
Got it
Than? how so
So you mean interaction endpoints don't have ratelimit at all? That's hella weird
This is how I am using it
or discord ws latency
It's not since they're valid once per interaction
You can only respond to an interaction once
This is fine
As I create a economy command, I've been looking for time and do not think
Wot ? New to discord.py ?
!d discord.Client.latency
property latency```
Measures latency between a HEARTBEAT and a HEARTBEAT\_ACK in seconds.
This could be referred to as the Discord WebSocket protocol latency.
no
Then wot u want to create ?
yes
I think it's friendlier to rest at UTC.
Or it you want to automate it use task
It's not that, I want to "create" an "economy" command containing daily, pay and atm
Explain command ? What will it do ?
What's its inputs ?
it's like Loritta's command
Who is Loritta
an economy command is a command that when you write "<prefix>daily" you will earn a money, and to see the money earned have to use "<prefix>atm" to see the money. In case I want to pay any user I have to use " <prefix>pay." Did you understand?
bot
He/she already got that I think.
wdym just put choice? replaced .readlines with choice or??
Use db , for daily use cooldown and for pay and atm use db querys !!!!!!
how can i make my bot work for the people wo have mod role only
Luc means prepared statements.
not like command
don't work
Check !!
the whole bot
!d discord.ext.commands.has_role
@discord.ext.commands.has_role(item)```
A [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that is added that checks if the member invoking the command has the role specified via the name or ID specified.
If a string is specified, you must give the exact name of the role, including caps and spelling.
If an integer is specified, you must give the exact snowflake ID of the role.
If the message is invoked in a private message context then the check will return `False`.
This check raises one of two special exceptions, [`MissingRole`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.MissingRole "discord.ext.commands.MissingRole") if the user is missing a role, or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") if it is used in a private message. Both inherit from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").
Changed in version 1.1: Raise [`MissingRole`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.MissingRole "discord.ext.commands.MissingRole") or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") instead of generic [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure")...
i know that
i want to make whole bot unusable
isnt it possible?
think you do not understand, I want to "know" how to create a python economy command, I do not know how to create
Then don't turn it on.
..
Not possible u have make each command indipendently
@limber bison
are you trying to make an economy bot?
yes
its not that hard
i mean i have the latency for bot
I want the latency for discord ws
Ohhh , any idea about commands.Cog ?
do you know json?
yes
We're not supporting and suggesting Json here.
Which command u make in past ?
Because json isn't a database
wdym
diversion
is it another language?
yes, python
lol
!d discord.ext.commands.Cog.bot_check
bot_check(ctx)```
A special method that registers as a [`Bot.check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.check "discord.ext.commands.Bot.check") check.
This function **can** be a coroutine and must take a sole parameter, `ctx`, to represent the [`Context`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Context "discord.ext.commands.Context").
Works like cog_check
do you know how to create an economic command?
that place is so weird
i do
but looks like i cant help you here
because its not a 'database'
https://github.com/AyushSehrawat/eco-bot
This will help u ,
Also watch vidio on cogs and db
You use a relative database and then make commands to support it with.
then dont start it bro ๐
This is json based...
Which is better discord.py or hikari
In this video, we learn about cogs and how to implement them in a discord bot.
If you have any suggestions for future videos, leave it in the comments below.
GITHUB: https://github.com/Rapptz/discord.py
DOCUMENTATION: https://discordpy.readthedocs.io/en/latest/
OFFICIAL DISCORD.PY SERVER: https://discord.gg/r3sSKJJ
JOIN MY HELP SERVER: https:...
d.py is more beginner friendly
i want to make it unusable for members who dont have mod role
neither, just use regular discord api
thatst jsut me tho
!d discord.commands.has_permissions
Nope
!d discord.ext.commands.has_permissions
@discord.ext.commands.has_permissions(**perms)```
A [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that is added that checks if the member has all of the permissions necessary.
Note that this check operates on the current channel permissions, not the guild wide permissions.
The permissions passed in must be exactly like the properties shown under [`discord.Permissions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions "discord.Permissions").
This check raises a special exception, [`MissingPermissions`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.MissingPermissions "discord.ext.commands.MissingPermissions") that is inherited from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").
Hmm
Just a single file ๐
is there any way to make my bot work with two prefix
It's db depended
and each prefix work for different command
y tho?
for example ! for games and . for mod commands
readlines returns a list and choice takes a list as argument and returns random item from it. Logic
Could you link me that API or smth
What is a good discord.py tutorial
maybe, i would try adding both as allowed prefixes then using a global/decorator check to conditionally allow the command based on ctx.prefix
alright so here is the the code: @bot.command() async def wyr(ctx): with open("wyr.txt", "r") as f: await ctx.reply(f.choice())
But it gives the error that there is no attribute called 'choice'
already did
!d random.choice
random.choice(seq)```
Return a random element from the non-empty sequence *seq*. If *seq* is empty, raises [`IndexError`](https://docs.python.org/3/library/exceptions.html#IndexError "IndexError").
random.choice() is a function provided by the random library, so you need to use it as random.choice(...)
... would be the list of lines you've read from the file
so would it be the amount or the acutal text?
how can i timeout people with my bot?
!d discord.Member.timeout
await timeout(until, /, *, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Applies a time out to a member until the specified date time or for the given [`datetime.timedelta`](https://docs.python.org/3/library/datetime.html#datetime.timedelta "(in Python v3.10)").
You must have the [`moderate_members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.moderate_members "discord.Permissions.moderate_members") permission to use this.
This raises the same exceptions as [`edit()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member.edit "discord.Member.edit").
!d discord.ext.commands.when_mentioned_or
discord.ext.commands.when_mentioned_or(*prefixes)```
A callable that implements when mentioned or other prefixes provided.
These are meant to be passed into the [`Bot.command_prefix`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.command_prefix "discord.ext.commands.Bot.command_prefix") attribute.
Example
```py
bot = commands.Bot(command_prefix=commands.when_mentioned_or('!'))
```...
the specific usage of .timeout() depends on the library you're using
so what should i do
ctrl+F for timeout( in the API Reference for whichever library you're using
I don't have one, I just understood how google was doing these searches and I modified it to do my searches from a command in my bot
pretty sure it all same for discord nextcord pycord and disnake i think๐
anyway to get message content via a reaction?
nah the syntax is slightly different
@bot.command()
async def timeout(message: commands.Context, member: discord.Member, until: int):
handshake = await timeout(user_id=member.id, guild_id=message.guild.id, until=until)
if handshake:
return await message.send(f"Successfully timed out user for {until} minutes.")
await message.send("Bunu yapamam.")```
it that code ok?
timeout() should be called from the member object
e.g. member.timeout(...)
its how you use any instance method like what you wrote, message.send()
alright
it said member object has no attribute named timeout
are you using discord.py 1.7?
run pip list in your terminal and look for a line starting with discord.py
pip show discord.py
sure
1.7's using a deprecated version of the discord gateway which doesnt have member timeouts
temp muting someone is a bit more complicated to implement but you could
im sure i can make it
Member.edit()
discord.py 2.0: timed_out_until = Optional[datetime.datetime]
pycord: communication_disabled_until = Optional[datetime.datetime]
disnake: timeout = Optional[Union[float, datetime.timedelta, datetime.datetime]]
nextcord: timeout = Optional[Union[datetime, timedelta] (yes, their doc is missing a closing bracket)
Member.timeout()
discord.py 2.0: timeout(until, /, *, reason=None)
pycord: timeout(until, *, reason=None)
disnake: timeout(*, duration=..., until=..., reason=None)
nextcord: timeout(timeout, *, reason=None)
other methods:
disnake: Guild.timeout(user, *, duration=..., until=..., reason=None)
pycord: Member.timeout_for(duration, *, reason=None)
slightly diff
by learning python
I know
oop and async mostly uk?
I know it's basics
@bot.command()
@commands.is_owner()
async def view(ctx,arg):
with open(arg+'.txt', "r") as f:
[await ctx.reply(line) for line in f.readlines()]``` why does this code send each line in a message?
ok so next step choose ur lib
discord.py nextcord pycord disnake hikari etc
Hmm
thats how u programmed it
How to print all lines in one message?
hikari for slightly advanced knowledge base for u i recommend dpy or disnake syntax mostly same u can just switch name between those 4 and be fine 99% of the time
story = f.read()
await CTX.reply(story)
ignore capital my keyboard ๐ฟ
okay
I am trying to make a currency bot in discord.py. I made it that it will store add 5 cookies everytime the user messages.
Now how can I make a jar command to check how many cookies does a user have?
here is my code
import discord
from discord.ext import commands
import json
bot = commands.Bot(command_prefix='> ', intents=discord.Intents.all())
@bot.event
async def on_ready():
print("Bot is Now Online")
@bot.event
async def on_message(message):
user_id = str(message.author.id)
with open("jar.json", "r") as file:
jar = json.load(file)
if not user_id in jar:
jar[user_id] = {}
jar[user_id]["cookies"] = 0
[user_id]["cookies"] += 5
with open("jar.json", "w") as file:
json.dump(jar, file)
await bot.process_commands(message)
@bot.command()
async def jar(ctx):
user_id = str(ctx.author.id)
with open("jar.json", "r") as f:
jar=json.load(f)
cookie_amt=jar[user_id]["cookies"]
await ctx.author.send(f"You have {cookie_amt} cookies in your jar.")
bot.run(token)```
json database ๐
yup
idk for some reason the jar command is not responding
no outputs
either
ty
@bot.command()
async def jar(CTX: commands.Context, user: discord.Member=None) -> None:
member = user or CTX.author
with open("jar.json") as f:
data = json.load(f)
await CTX.send(data[member.id]["cookies"])
ctx capital?
๐ญ
in on_message do jar[user][cookie] += 5
and the annotation is incorrect
the annotation is fine from dpy's perspective
but 8ster's code appears to be valid anyway
id try adding a print statement on top of on_message to make sure its registering your message at least
it is I tested it
check json for cookies
it works but it should be Member | None
added or not
it does
import random
import asyncio
from time import sleep
at0, at1, at2, at3, at4 = 0, 0, 0, 0, 0
atlar = [at0, at1, at2, at3, at4]
while all(at < 5 for at in atlar):
for i in range(5):
sayi = random.randint(0,1)
print("-" * atlar[0] + "๐",",", "-" * atlar[1] + "๐",",", "-" * atlar[2] + "๐",",", "-" * atlar[3] + "๐",",", "-" * atlar[4] + "๐")
atlar[i] += sayi
asyncio.sleep(delay=0.5)
winner = atlar.index(5)
print("winner is", atlar[winner]) # THAT'S NOT WORKING```
how can i make it print the winner at the end
will be that a not be a error
becasue in cookie is not already defined
I did, now I'm getting the same error when I type "GUILD"
import os
import discord
from dotenv import load_dotenv
load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')
client = discord.Client()
@client.event
async def on_ready():
for guild in client.guilds:
if guild.name == GUILD:
break
print(
f'{client.user} is connected to the following guild:\n'
f'{guild.name}(id: {guild.id})'
)
client.run(TOKEN)
where is guild defined?
your trying to compare guild.name to GUILD, which isnt defined and doesnt exist
Can someone remind me which attribute of command returns the command arguments?
it was get_signature i think
.signature
get_command_signature
!d discord.ext.commands.Command.signature
property signature```
Returns a POSIX-like signature useful for help command output.
The list of transformed arguments that were passed into the command. If this is accessed during the on_command_error() event then this list could be incomplete.
was looking for the signature, thanks
import os
import discord
from dotenv import load_dotenv
load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')
client = discord.Client()
@client.event
async def on_ready():
print(f'{client.user.name} has connected to Discord!')
@client.event
async def on_member_join(member):
await member.create_dm()
await member.dm_channel.send(
f'Hi {member.name}, welcome to Sparks Place! This bot was programmed by yours truly, Sparkpf#3258'
)
client.run(TOKEN)
Why does it not send a dm to my alt when I Join?
!d discord.Member.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**.
what's the obvious error here? ```py
for command in bot.commands:
help_text.append(f'{command.name}\n{command.doc}')
print(help_text)
I want to pin a message but this error came
msg = await interaction.send(embed=embed)
await msg.pin(reason="Handling")
command._doc_ isn't documented so I'd say that's a possible error
ah. I thought it would return the function doc
but I guess command.brief is for that
command.callback._doc_ would work
command.description would return that directly i think
would have to check source for that
command.description searches for the description kwarg else it returns the docstring yes
interactions are not messages
nor are responses
so i cant pin them?
``@bot.slash_command(guild_ids=[settings["guildID"]], name="stock", description="Allows you to see the current stock.")
async def stock(ctx: discord.ApplicationContext):
if not isWhitelisted(ctx):
return ctx.respond("Only whitelisted users can use this command.")
return await ctx.respond(
f"```Current Nitro Tokens Stock: {len(open('tokens.txt', encoding='utf-8').read().splitlines())}```")``
I want to make from f"```Current Nitro Tokens Stock: {len(open('tokens.txt', encoding='utf-8').read().splitlines())}```") An Embed, can someone help
....................................
shouldnt it be
embed = discord.Embed(title="", description="")
await ctx.send(embed=embed)
idk if im wrong, i use nextcord
is this a rac casino command ?
or a fun game ?
hm yes if it's not a slash command
oh
maybe its like nextcord?
interaction.send(embed=embed)?
i have json embed file how can i create embed vai python just puting json in code ?
Someone?
you can't really do much other than sending a normal message and then pinning it instead of sending an interaction response and wanting to pin it
@slate swan Can you help
what's the issue
!d discord.Embed
class discord.Embed(*, colour=None, color=None, title=None, type='rich', url=None, description=None, timestamp=None)```
Represents a Discord embed.
len(x) Returns the total size of the embed. Useful for checking if itโs within the 6000 character limit.
bool(b) Returns whether the embed has any data set.
New in version 2.0.
x == y Checks if two embeds are equal.
New in version 2.0...
But it dont wokrk
I have already tryed
Can u maybe make it, it will help me alot
I dont ask you
who asked
and several hard no(s)
Lol
u need to add fields after instantiating the embed object
Hello.
Bro not my fault
Hi

This tone isn't appropriate. Have you read our #code-of-conduct ?
stockVar = discord.Embed(title="Test", description="**Test*") ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='?
``@bot.slash_command(guild_ids=[settings["guildID"]], name="stock", description="Allows you to see the current stock.")
async def stock(ctx: discord.ApplicationContext):
if not isWhitelisted(ctx):
return ctx.respond("Only whitelisted users can use this command.")
return await(
stockVar = discord.Embed(title="Test", description="**Test*")
stockVar.set_image(url="Test")
await ctx.respond(embed=stockVar))``
call the object u created and use the class method add_field
Can u show how
But it is not that error
the syntax at the end is just wrong
Lol
what are you trying to await there
Idk
return await(
stockVar = discord.Embed(title="Test", description="**Test*")
stockVar.set_image(url="Test")
await ctx.respond(embed=stockVar))
that doesnt even make sense like, god
Removed Await but still the same error
you can't just type stuff and expect it to work
Bro
what
This discord is for help, and you guys dont help
ok nice
then stop asking for help here
No
Bro go away, your an so stupid
!shhh
โ silenced current channel for 6 minute(s).
If you don't wish to assist someone then you are welcome to remain silent. Negative comments toward others without any offer of help are just not welcome. If someone doesn't know how to ask the question, you're all welcome to guide them but you are not welcome to bash them.
@slate swan Calling people names and telling them to stfu regardless of their actions is not going to fly here. I suggest you stop.
!unshush
!unhush
โ unsilenced current channel.
Darn "s" 
embed=discord.Embed()
embed.add_field(name="undefined", value="undefined", inline=False)
await ctx.send(embed=embed)
But
I need to add an field that says the stock
You know what i mean?
He needs to tell the lines of tokens.txt & count it x2
Hi, how i can fix that?...
yea..
which lib is that
discord.py v2
re-sync the tree
@wise mulch
Get this error
File "/home/container/main.py", line 161 embed=discord.Embed() ^^^^^^^^^^^^^^^^^^^^^ SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='?
resync the tree
how
comment out all the slash commands, then run your code and sync, so that it syncs an empty tree and cleans off all the commands from the discord api corresponding to your bot, then uncomment all the commands and sync again
stockVar = discord.Embed(title="Test", description="**Test*")
stockVar.set_image(url="Test")
await ctx.send(embed=stockVar))
oh, thx <33
stockVar = discord.Embed(title="Test", description="**Test*") ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='?
Still get this error
hard to tell without seeing the code, seems right syntax
mysql vs postgresql / which is best for new ones ? new to realtional db ?
``
@bot.slash_command(guild_ids=[settings["guildID"]], name="stock", description="Allows you to see the current stock.")
async def stock(ctx: discord.ApplicationContext):
if not isWhitelisted(ctx):
return ctx.respond("Only whitelisted users can use this command.")
return(
stockVar = discord.Embed(title="Test", description="**Test*")
stockVar.set_image(url="Test")
await ctx.send(embed=stockVar))
`` this is the code @wise mulch
.bm add this to the pile of how-tos
What you are were actually doing is
return await(embed = discord.Embed() embed.set_image() await ctx.respond())
which simply doesnt make sense since you cannot assign variables while using a return statement and the await never even works outside the parentheses here. You have to create variables outside an await or return statement and only await the send method
@client.command()
@commands.has_guild_permissions(ban_members=True)
async def unban(ctx, *, member):
banned_users = await ctx.guild.bans()
member_name, member_discriminator = member.split("#")
for ban_entry in banned_users:
user = ban_entry.user
if(user.name, user.discriminator) == (member.name, member_discriminator):
await ctx.guild.unban(user)
await ctx.send(f"Successfully unbanned **{user.name}** !")```
I just spotted a typo, thanks and thanks
can anyone help with that
what's the isue?
# bot.py
import os
import random
from discord.ext import commands
from dotenv import load_dotenv
load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')
bot = commands.Bot(command_prefix='!')
@bot.command(name='rmsg')
async def nine_nine(ctx):
choice_messages = [
'You\'ve ran the random message command, this is a random message out of 5! (1/5)',
'Hi? (2/5)',
'Who are you? (3/5)',
'ayo bro (4/5)'
'I am bored (5/5)'
]
response = random.choice(choice_messages)
await ctx.send(response)
bot.run(TOKEN)
It says I'm missing intents on line 12, what do I do?
Lucas ban 
@wise mulch
Now i get this error
if not isWhitelisted(ctx): ^ IndentationError: unindent does not match any outer indentation level
mysql vs postgresql / which is best for new ones ? new to realtional db ? @silk fulcrum ?
my ,unban command doesnt work
lucas unban . youtube
check your spacing
Wdym
if you have recently switched to 2.0, then intents are now a required argument to be passed in to commands.Bot. This usually includes the Members and Message Content intents to be enabled. Honestly, depends on your use case. But make sure to enable the Message Content intent otherwise your prefix (message) commands will NOT work
nice; really helpful, what's the error
!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
Okimii study Visual Basic for me 
heck no, visual basic makes me wanna vomit๐ญ
me too but exam
# bot.py
import os
import random
import discord
from discord.ext import commands
from dotenv import load_dotenv
load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')
intents = discord.Intents.default()
intents.members = True
intents.message_content = True
bot = commands.Bot(command_prefix='!')
client = discord.Client(intents=intents)
@bot.command(name='rmsg')
async def nine_nine(ctx):
choice_messages = [
'You\'ve ran the random message command, this is a random message out of 5! (1/5)',
'Hi? (2/5)',
'Who are you? (3/5)',
'ayo bro (4/5)'
'I am bored (5/5)'
]
response = random.choice(choice_messages)
await ctx.send(response)
bot.run(TOKEN)
like this?
"to be passed in to commands.Bot" not a new client please, it's just bot = commands.Bot(command_prefix="!", intents=intents)
!d discord.Embed
class discord.Embed(*, colour=None, color=None, title=None, type='rich', url=None, description=None, timestamp=None)```
Represents a Discord embed.
len(x) Returns the total size of the embed. Useful for checking if itโs within the 6000 character limit.
bool(b) Returns whether the embed has any data set.
New in version 2.0.
x == y Checks if two embeds are equal.
New in version 2.0...
@wise mulch
I have fixed it, but now i need to make that it counts each line in tokens.txt & it wil send in the embed
haven't done that one, not sure.
lol degradation
How do I make it send an embed
!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**.
embed kwarg
I still don't get it
sad
for line in open("tokens.txt"): count += 1 varstock=discord.Embed(title="Tiqs | Stock") varstock.add_field(name="($count)", value="Count", inline=False)
But now i get in the embed ($count)
And not the count
what
Is there any tutorial that will explain embeds and not just send some code I don't understand
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: UnboundLocalError: local variable 'count' referenced before assignment
I really really dont wanna say it, because they're realllyyyy bad... but probably yt tutorials containt how to send embeds
full exception
Traceback (most recent call last): File "/home/container/.local/lib/python3.10/site-packages/discord/bot.py", line 992, in invoke_application_command await ctx.command.invoke(ctx) File "/home/container/.local/lib/python3.10/site-packages/discord/commands/core.py", line 358, in invoke await injected(ctx) File "/home/container/.local/lib/python3.10/site-packages/discord/commands/core.py", line 135, in wrapped raise ApplicationCommandInvokeError(exc) from exc discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: UnboundLocalError: local variable 'count' referenced before assignment
``async def stock(ctx: discord.ApplicationContext):
for line in open("tokens.txt"): count += 1
varstock=discord.Embed(title="Tiqs | Stock")
varstock.add_field(name=count, value="Count", inline=False)
if not isWhitelisted(ctx):
return ctx.respond("Only whitelisted users can use this command.")
if isWhitelisted(ctx):
await ctx.send(embed=varstock)``
link?
nah, im eating dinner, watching chess video and helping 2 people
How do you error handle @commands.has_role()?
@silk fulcrum Did you know it?
nvm
uhm... i guess you didnt define count and using it in count += 1
so just do count = 0 at the sturt of func
Ok
just usual error handler
yup
I wish there was a way to hide slash commands for specific roles
like moderation commands
if for specific command:
@that_command.error
async def on_that_command_error(ctx, error):
if isinstance(error, commands.MissingRole):
do_whatever```
if for all commands: the same but creating an event on_command_error
i dont think so
but i think so
idk, im not sure
!d discord.Embed
b"py\n\nclass discord.Embed(*, colour=None, color=None, title=None, type='rich', url=None, description=None, timestamp=None)\nRepresents a Discord embed.\n\nlen(x) Returns the total size of the embed. Useful for checking if it\xe2\x80\x99s within the 6000 character limit.\n\nbool(b) Returns whether the embed has any data set.\n\nNew in version 2.0.\n\nx == y Checks if two embeds are equal.\n\nNew in version 2.0..."
You can do checks
What do you mean?
Lmao
@commands.has_permissions() or something similar
@silk fulcrum pop up the docs for checks
it won't hide the command
@silk fulcrum How can i get like
varstock.add_field(name=None, value="Tiqs has", value=count, value="Server Boosts", inline=False)
- open docs
- go to search
- search for checks
You know what i mean
stoooop spamming
I dont spam lol
If I needed it id have it alr
but how can i do this
no
But it will prevent non mods from using it
yeah but they wanted to hide it
but wont hise the command
I want
Tiqs has (count) boosts
And not
Tiqs has
Count
Boosts
U only have one value arg
!f-strings
Creating a Python string with your variables using the + operator can be difficult to write and read. F-strings (format-strings) make it easy to insert values into a string. If you put an f in front of the first quote, you can then put Python expressions between curly braces in the string.
>>> snake = "pythons"
>>> number = 21
>>> f"There are {number * 2} {snake} on the plane."
"There are 42 pythons on the plane."
Note that even when you include an expression that isn't a string, like number * 2, Python will convert it to a string for you.
Well.. thats... something 
btw i think I saw the absolute similar bug today, but I didnt really realise it was wrong
first time?๐ญ
@slate swan
or wait
wut

master did you see my awesome thnig i made
I don't pay much attention to embeds. Can't see them on most my machines. Not sure why that one is feeling a bit glitchy. 
count = 0 for line in open("tokens.txt"): count += 2 varstock=discord.Embed(title="Tiqs | Stock") varstock.add_field(name=None, value="Tiqs has {count} boosts", inline=False) varstock.set_thumbnail(url="https://cdn.discordapp.com/attachments/937356474210979860/1008267653565140992/925FBE55-A0A6-4105-942E-D26AC99F8CAB.gif")
Whats the problem
string literal needs to prefixed with f
my cat cannot walk on one of my wardrobe's shelves properly, because he is 7 kilo and that shelve is like... idk, from paper
Oh
But how can i get count there?
^
you already got it
prefix the string literal with f
you can achieve this by adding an f to the start (prefix) of the string
i use uppercase F๐ณ
๐ซ
sociopathic qualities

I'm getting a 403 forbidden error when attempting to add this user to the thread. I have admin perms for the bot. The users reacting to the message also have perms to change threads. The channel the messages are appearing in also allows threads to be created.
Think i fixed it by making the thread public.
@bot.event
async def on_reaction_add(reaction: nextcord.Reaction, user: nextcord.User):
if reaction.emoji == 'โ
' and not user.bot:
await reaction.message.clear_reactions()
await reaction.message.add_reaction('๐')
await reaction.message.edit(content=f'Approved by {user.mention}')
message_content = reaction.message.content
print(message_content)
elif reaction.emoji == 'โ' and not user.bot:
await reaction.message.clear_reactions()
await reaction.message.add_reaction('โ')
create_thread = await reaction.message.create_thread(name=f'Application was denied by {user.name}')
for field in reaction.message.embeds:
user_id = int(field.fields[0].value)
user_to_add = reaction.message.guild.get_member(user_id)
await create_thread.add_user(user_to_add)
break
Stupid