#discord-bots
1 messages · Page 989 of 1
8.2. The while statement
The while statement is used for repeated execution as long as an expression is true:
while_stmt ::= "while" assignment_expression ":" suite
["else" ":" suite]
``` This repeatedly tests the expression and, if it is true, executes the first suite; if the expression is false (which may be the first time it is tested) the suite of the `else` clause, if present, is executed and the loop terminates.
A [`break`](https://docs.python.org/3/reference/simple_stmts.html#break) statement executed in the first suite terminates the loop without executing the `else` clause’s suite. A [`continue`](https://docs.python.org/3/reference/simple_stmts.html#continue) statement executed in the first suite skips the rest of the suite and goes back to testing the expression.
https://paste.pythondiscord.com/ebuzejefok The code ive got works perfectly and posts all the chat logs the first time the code executes. but then when the loop comes after 30 seconds it doesn't post. I've been advised that its re-using the same cursor and it i need to make it create a new cursor? Could anyone help me, i dont fully understand how to do it. Been stuck with this problem for a good 4 weeks now, id really appreciate any help 🙂
client.crypto_pages = [cryptoEmbed, cryptoEmbed2, cryptoEmbed3, cryptoEmbed4, cryptoEmbed5, cryptoEmbed6, cryptoEmbed7, cryptoEmbed8]
current = 0
async def button_callback(interaction):
await interaction.response.edit_message(content=client.crypto_pages[current+1])
msg = await ctx.send(embed=client.crypto_pages[current], view=view)```
i was trying to scroll through embed pages using buttons but for some reason the interaction.response.edit_message part doesn't seem to do anything rn. did i mess up smt?
How do i fix the module error:
No module found named discord.commands
?
what did u input
Import?
yes
from discord.commands import Options
how do u use options
In a Dropdown menu
hi soo i ve seen a lot of people talking about self-bots and I know they are against Tos and i dont intend to breach it but justout of curiosity how do u make a self-bot
The weird thing is, if i host the bot on my pc it works, but on an raspberry it gives this error
its going inside discord appfiles and changing it which is against tos
ohh
hmm
So i think i need to install something on the rpi what i already did on my pc
But i dont know what
in python they will prolly use something like selenium ig
It's discord.ext.commands
And pretty sure the components are in discord.ui
No module found named discord.commands
there is nothing called Option in discord.ext.commands
hood mornin'

how to set volume of the bot
When checking if something is equal to one thing or another, you might think that this is possible:
if favorite_fruit == 'grapefruit' or 'lemon':
print("That's a weird favorite fruit to have.")
While this makes sense in English, it may not behave the way you would expect. In Python, you should have complete instructions on both sides of the logical operator.
So, if you want to check if something is equal to one thing or another, there are two common ways:
# Like this...
if favorite_fruit == 'grapefruit' or favorite_fruit == 'lemon':
print("That's a weird favorite fruit to have.")
# ...or like this.
if favorite_fruit in ('grapefruit', 'lemon'):
print("That's a weird favorite fruit to have.")
if any(x for x in [hc, gm, ac] if x in user.roles)
or if hc in user.roles or gm in user.roles or ac in user.roles
Any error?
lemme recode it
How can I make this thing in economy were if you buy something it will give me money every somthing seconds e.g I buy I manager then the manager gives me money every 3 minutes
@bot.command()
async def demote(ctx, user: discord.Member):
hc = discord.utils.get(ctx.guild.roles, name="Head Coach")
gm = discord.utils.get(ctx.guild.roles, name="General Manager")
ac = discord.utils.get(ctx.guild.roles, name="Assistant Coach")
if roles := list(filter(lambda r: True if any(x for x in [hc, gm, ac] in user.roles) else False, user.roles)):
await user.remove_roles(roles)
embed = discord.Embed(title="Demotion Complete!", description=f"{user.mention} has been demoted from ``{', '.join(roles)}``!\n > **Franchise Owner:** {ctx.author.mention}", color=0x2C2F33)
embed.set_author(name=ctx.guild.name, icon_url=str(ctx.guild.icon_url))
embed.set_image(url="https://cdn.discordapp.com/attachments/898576566299262987/963653507490136094/final_62564dcc1a766400850b76de_691951.gif")
msg = await ctx.reply(embed=embed)
await msg.add_reaction(':white_check_mark:')
print(f'Demotion Complete |\n Player: {user}\n {', '.join(roles)}: {ctx.author}')
await user.send(f'{user.mention} you have been demoted from ``{', '.join(roles)}`` in ``{ctx.guild.name}`!')
else:
print(f'Demotion Failed |\n Player: {user}\n Coach: {ctx.author}\n No coach roles')
await ctx.reply(f'`{user}` does not have any coach roles!')
How can I make this thing in economy were if you buy something it will give me money every somthing seconds e.g I buy I manager then the manager gives me money every 3 minutes
?
So e.g i buy a Manager and I get money every 3 minutes
By using a task
How can I use task
How would i use task by using economy?
Did you read the doc?
I don’t use cogs
This can also be used outside cogs.
Oh
from discord.ext import tasks
@tasks.loop(seconds=5.0, count=5)
async def slow_count():
print(slow_count.current_loop)
@slow_count.after_loop
async def after_slow_count():
print('done!')
slow_count.start()
Like that?
You just copied the example 
I know
But I know how to change it
How to make discord slash command only visible to user
You need the import yes but I assume you want it to never end when the bot starts.
Not possible yet, per guild is.
Yes per guild works
Correct!
Wait it ends?
Per user slash visibility.
there is a keyword arg called ephemeral, if u set it to True, only that user can see it
This one does since count=5
That's not the same as per user visibility.
So I delete that?
yes that’s it
ah they want only certain people to access slash commands, i c
That's ephemeral not the same.
So I delete that? Count=5
About time.
Still that would most likely only work with permissions meaning custom checks still will be visible.
Among other things.
Like what?
Well you don't need an after loop
No I don’t
You just need the loop and add x amount of money.
Oh ok
Tbh Slash in discord.py is still a mess.
?
True I almost tackled that issue tough
setup hook
@slate swan We talked about this lol
That's the most weirdest way to do this.

And according to Danny setup hook only runs once on launch so that would be a flaw in his own code.
Do I put the task inside my command?
No.
Where then?
Anywhere you want.
How will it know what to do
Because I want to do a thing where you buy something and gives you money every 3 minutes
!d discord.ext.tasks.loop
discord.ext.tasks.loop(*, seconds=..., minutes=..., hours=..., time=..., count=None, reconnect=True)```
A decorator that schedules a task in the background for you with optional reconnect logic. The decorator returns a [`Loop`](https://discordpy.readthedocs.io/en/master/ext/tasks/index.html#discord.ext.tasks.Loop "discord.ext.tasks.Loop").
Honestly not including auto sync is a problem waiting to happen.
How can I connect it to my command
How can I connect it to my command
nice tag
you do not connect it to a command, you'll declare this somewhere in your code and it will run automatically when the time you declared passed
How?
Ah okay well not syncing when nothing changed does make sense, so I will most likely code my own auto sync and detect changes to any parts of those code.
That could've easily be added to the main lib.
Well as long as you never change the slash sync command you can also just use a slash command that is registered to a specific guild.
examples/background_task.py line 6
class MyClient(discord.Client):```
Could I use asyncio.sleep?
you don't need the sleep
Only once then you can remove it.
I don’t understand?
guild specific syncs are instant.
examples/background_task.py line 21
@tasks.loop(seconds=60) # task runs every 60 seconds```
what is hard about this?
How could I do that but using a command
Still if this wouldn't get changed I would honestly recommend everyone that wants slash commands to just code it in js or rust.
There is no sense to make a loop that runs in a command
I guess you could start/stop the loop there.
you can do that too with loops by creating a bot variable that tells you if the loop should run or not 
Do I do @my_task_name.command
no you just do @tasks.loop(time)
Just 1 basic command, if you do nothing too fancy it's pretty doable.
Like say my bot is an economy bot and then I hire a manager the manager will make money for you every 3 minutes and I could use @peak geodes.loop to give the money every 3 minutes
Plus the libraries, compared to discord.py theirs is so up to date.
yeah.. so what do you not understand with this? 
How could I do that with tasks
a tasks is just a block of code which runs every x time, in that block of code you can do whatever you want
Oh
just check if you have a manager like you would do for other things and if so give the money
the loop manage the Asyncio for you .-.
from discord.ext.tasks import loop
@loop(minutes=3)
async def my_loop():
print("This message will be printed in the console every 3 minutes")
Could I put that inside my command?
My god it doesn't go into a command
check this block of code
it is inside a command? no
it is an external function
put the task where you created the instance of your bot
you check it inside the loop function
Ohhhhhh

how you declare the manager?
In like a Shop thing
yeah i want to know what you do with it, you save it in a database, you just assign a variable to it? what this manager is in your code?
for member in role.members:
await member.remove_roles(role)
# Avoiding rate limit
await asyncio.sleep(1)
i think that 1 secs will not help lol
Depends on how many users are in the role lol
he could've bought discord users somewhere and have like 400 people in his testing server 
Why would you need 400 users for a test server
I’m using json

Not database
why i'm not surprised about it?
json is not a storage method, it is a way to represents javascript objects in text files
^
if user has name=“laptop”
[give the person the money]
Is that a option?
If the nickname is laptop?
Yes it is
Could you please stop sending this without any context?
I meant to send it earlier but bad internet
json is a data format*
!d discord.Member.display_name returns the nickname of the member
property display_name```
Returns the user’s display name.
For regular users this is just their username, but if they have a guild specific nickname then that is returned instead.
pretty sure last time i checked the json stands for "JavaScript Object Notation"
btw, hello Ash
yeah, so?
its a format to write data in
No?
You can use it to do it but it was not designed for that 
nvm I meant something else
i should have used as instead of in for better understanding
well you know when you have to think like a compiler you take everything literally
well
Depends on the compiler lol
HAHAHAHAHAHAHAAH
@slash.slash(name="test", description="test", guild_ids=[958975820469256233], options=[create_option(name="input", description="test", required=True, option_type=3)])
async def user(ctx: SlashContext, username:str):``` how to use ephemeral
You send it with the message.
I hated js cz of that fr 😔
!d discord.MessageFlags.ephemeral
Returns True if the source message is ephemeral.
New in version 2.0.
js errors gives me headaches
as far as i think, they are using discord_components
await ctx.send(embed=e, ephemeral=True)
then it's still the same.
same, first of all they arent really clear
hm yeah
Wait no ephemeral is called hidden in that lib
Same goes for slash_command
I’m using discord-py-slash-commands

ephemeral keyword is only for interactions
I was coding a basic js bot then it gave me a weird error with a lot of error codes all because I didn't pass one specific intent.
Ok
js stands for JavaShit
Wha
Trust me this is how they made the slash command.

W
Well aside from it's really bad error indicator the language itself is pretty nice.
But it does make browsing a pain since every company these days use js to handle data.
For website processing.
lol
nah javascript is good
who would code a bot with js 😔
I got it hidden=True
a lot of people 
Because there strange
I said this almost 20 min ago #discord-bots message
I didn’t see that sorry
Yo
how do i update a print without having to print it again
async def register(ctx):
con = lite.connect('user_data.db')
with con:
cur = con.cursor()
cur.executescript("""
DROP TABLE IF EXISTS user_data;
CREATE TABLE user_data(UserID TEXT, Cash INT);
INSERT INTO user_data VALUES(message.author.id,0)
""")```
it doesnt work.. pls help
lmao
u dropping al the data to isert 1 record if im right
hi
heyo 👋


uh.....? inappropriate channel
go to #python-discussion and ill help u
bru
dedication
hello plz tell me how can i get @PyDis Core Developers this role
and?
Why the cmd get context().prec = any number not worked in pycharm
Any number here is like 20, 30, etc .
Any1 here???
Ig no 😅
what is get context().prec = any number supposed to do?
It show the total numbers of the result example if 10/3 is 3.3 and we put the any number is equal to 30 it will have 3,3333(25more 3), the normal if we dont do the cmd is 15 ig
@slate swan With SQL WHERE clause and by invoking register.
I'm watching Netflix rn i don't really want to switch between dm and channel lol
thats it
ok
how to do it?
and also how to view table? @cloud dawn
i want to view the table with terminal*
it works for me

!e print(10/3)
@cloud dawn :white_check_mark: Your eval job has completed with return code 0.
3.3333333333333335
How to do what? I said 2 methods.
oh
No clue I don't really use sqlite.
thxs
async def balance(ctx):
con = lite.connect('user_data.db')
with con:
cur = con.cursor()
cur.executescript(print(SELECT DISTINCT Cash FROM message.author.id;))```
i dont know how to do this pls help me @cloud dawn
..
how to fix it then
cur.executescript("SELECT DISTINCT Cash FROM user_data WHERE UserID = ?;", (message.author.id,))
Also why do you drop the table if it exists.
kek
i dont need it?
async def balance(ctx):
con = lite.connect('user_data.db')
with con:
await message.channel.send(cur.executescript("SELECT DISTINCT Cash FROM user_data WHERE UserID = ?;", (message.author.id,)))```
it still not working, how to fix :/
would love to get some feedback on my first python disocrd bot coding tutorial in german, delete if advertising isnt allowed, https://www.youtube.com/watch?v=Kj1P-dVX4eM&t=3s
Die Grundlagen um einen eigene Discor-Bot zu erstellen.
CMD-Befehle:
python --version
pip --version
pip install discord
Links:
Mein eigener Bot: https://www.tr3xbot.me/
Discord Developer Portal: https://discord.com/developers/applications
Discord.py API: https://discordpy.readthedocs.io/en/stable/api.html
Python: https://www.python.org/downloa...
@cloud dawn
I really recommend learning the syntax first, I want to help but I'm not going to code it for you.
pls just for this part :/
and i will go learn it*
!d sqlite3
Source code: Lib/sqlite3/
SQLite is a C library that provides a lightweight disk-based database that doesn’t require a separate server process and allows accessing the database using a nonstandard variant of the SQL query language. Some applications can use SQLite for internal data storage. It’s also possible to prototype an application using SQLite and then port the code to a larger database such as PostgreSQL or Oracle.
The sqlite3 module was written by Gerhard Häring. It provides an SQL interface compliant with the DB-API 2.0 specification described by PEP 249, and requires SQLite 3.7.15 or newer.
Yes dont spoonfeed !
pls help me write this code part, just this once
discord.Intents().all() -> discord.Intents.all()
why not use something like this?
conn = sqlite3.connect('path/to/database.db')
c = conn.cursor()
def balance(id):
c.execute("SELECT cash FROM user WHERE userid=:id", {'id': id})
return c.fetchall()
get_balance = balance(007)
print(get_balance)
but yeah, one should learn the basic first, you won't learn anything otherwise
thxs
I also recommend listeners instead of events, plus f-strings. Other than that solid.
One of the better d.py tutorials.
difference between listener and events?
!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...
Is there any website for me to learn more python? i need to learn more
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
Thanks
yo help
class giveaway(commands.Cog):
"""huh4?."""
def __init__(self , bot: commands.Bot):
self.bot = bot
async def convert2(a1:int,a2:str):
pass
@commands.command(name="g")
async def giveaway(self, ctx):
if x in ["Start","start","st"]:
await convert2()
``` i cant acces
convert2()
Well since convert2 is in a class you need to pass self first or make it a @staticmethod.
And since it is a function inside the class you also need to call it using self, e.g self.convert2()
oh ye thanks
Realpython, geeksforgeeks, python documentation..
Thanks
Doesn't have geekforgeeks have a mandatory sign up these days?
theres a way to not sign up and still be able to view g4g
Anyone here ever had to deal with the bot sending messages twice (#help-pretzel)?
ya it sux :/
Only run the bot once.
is it possible to use a dropdown menu that would be up forever
Yup, I did (at least, I'm pretty sure I did)
like, no timeout
Did you check task manager?
2 python applications?
👀
But... how?
I'm only doing bot.run() once in my main.py
no like do u have main.py running twice
Nope, that's all in that image
Already tried
does it do it for all commands or only some?
I've narrowed down the problem to a Cog
All commands
I've posted code in #help-pretzel
# Load cogs
print("Loading Cogs:\n")
cogs = ["debug", "logging"]
for cog in cogs:
bot.load_extension(f"cogs.{cog}")
print(f" Loaded Cog: {cog}")
print("\nCogs loaded!")
# Run
bot.run(TOKEN)
When I have logging in there
it does the two messages thing
when loading is not there, it is fine
..
But that can't be causing the problem
what is the error?
There is no error, sorry
My discord bot just sends a message twice
he says he run only 1 python file but in run twice
of everything?
Yeah, whenever I use a command that makes it send a message, it sends it twice
check #help-pretzel
then you probably have 2 instances running
Here's my code for logging.py:
import discord
from discord.ext import commands
from datetime import datetime
class Logging(commands.Cog):
def __init__(self, bot: commands.Bot) -> None:
self.bot = bot
@commands.Cog.listener()
async def on_message(self, message: discord.message.Message):
# Current date-time in ISO-8601 format (without microseconds):
# yyyy-mm-ddThh:mm:ss±tmzn
time = datetime.now().astimezone().replace(microsecond=0).isoformat()
print(
f"[{time}] Message from {message.author} (Message ID: {message.id}, Message author ID: {message.author.id}): {message.content}"
)
await self.bot.process_commands(message=message)
def setup(bot: commands.Bot):
bot.add_cog(Logging(bot))
discord.message.Message doesn't exist.
lol
wait close ur VSC and see if the bot went offline or not @brisk dune
Like everyone here told him already.
it does tho but its just not the right name spaces
I could see if it works when I remove it
lol
!d discord.message.Message it exists
class discord.Message```
Represents a message from Discord.
x == y Checks if two messages are equal.
x != y Checks if two messages are not equal.
hash(x) Returns the message’s hash.
Nope
ok
Yup, the bot closes
as said on top!
try running python file directly from folder not vsc
No
now open cmd and run the bot from there and see if ur facing the same prob
I'll try
Yup, same problem
Nope
@brisk dune ?
ok, ur bot is cursed :/
Yup, still the same problem
show ur whole code and hide token
😱
A-Z
a-z
Hold on, going to paste to discord paste thing
!paste
Pasting large amounts of code
If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
it wont work though
like it wont go past the frist one
uh
...
Why though
huh
!d discord.Message is it the same
class discord.Message```
Represents a message from Discord.
x == y Checks if two messages are equal.
x != y Checks if two messages are not equal.
hash(x) Returns the message’s hash.
imagine context
only once for me ...
IDK mate, I did print(type(message)) in a command function to get the type of the message
👀
cool u tried
ur python is cursed
brb
🤏
its just name spacing the first one includes the file name but since the discord folder with all models has an init file it becomes a class bound to the module and not the file itself
so it wont be
package_name.file_dir/name.ClassName but package_name.ClassName
aka potential cursed typehints.
Nooooo!!!!! It still doesn't work!!!!
this func has 3 parame
async def convert2(cts,a1:int,a2:str):
but i can only acces 2
a = await self.convert2()
is it a class method or just a method?
i suppose its a method since the example below
..
Did you try out the loading.py cog as well?
class giveaway(commands.Cog):
"""huh4?."""
def __init__(self , bot: commands.Bot):
self.bot = bot
async def convert2(cts,a1:int,a2:str):
nah thats too much work
turn on the linter on ur ide
It's the loading.py cog that breaks it...
Without it, it works just fine
but that instance naming isnt correct. but self just means it should be a method of an instance of the class which it gets satisfied when you do ClassName().method()
u will have to download it something from the extentions marketplace
cts isnt correct and if it were a classmethod it would be cls
name?
linting
Name: Python
Id: ms-python.python
Description: IntelliSense (Pylance), Linting, Debugging (multi-threaded, remote), Jupyter Notebooks, code formatting, refactoring, unit tests, and more.
Version: 2022.4.1
Publisher: Microsoft
VS Marketplace Link: https://marketplace.visualstudio.com/items?itemName=ms-python.python
uh
That's the one I use
not u
await self.bot.process_commands(message=message) in ur on_message could be the reason, although i dont really know 🤷♂️
comment it out and see
Guess what works now...
or remove the message=message
Nah, that entire line was causing the message to be re-interpreted
process_commands inside a listener?, be ready to get double responses 😳
!d discord.ext.commands.Bot.process_commands
await process_commands(message, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
This function processes the commands that have been registered to the bot and other groups. Without this coroutine, none of the commands will be triggered.
By default, this coroutine is called inside the [`on_message()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_message "discord.on_message") event. If you choose to override the [`on_message()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_message "discord.on_message") event, then you should invoke this coroutine as well.
This is built using other low level tools, and is equivalent to a call to [`get_context()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.get_context "discord.ext.commands.Bot.get_context") followed by a call to [`invoke()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.invoke "discord.ext.commands.Bot.invoke").
This also checks if the message’s author is a bot and doesn’t call [`get_context()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.get_context "discord.ext.commands.Bot.get_context") or [`invoke()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.invoke "discord.ext.commands.Bot.invoke") if so.
Changed in version 2.0: `message` parameter is now positional-only.
When you do ctx.channel.send instead of ctx.send does that make it not usable in dm channels or no
I'm assuming no
TIL don't put commands.Bot.process_commands(message) in a cog
!d discord.ext.commands.Context.channel
Returns the channel associated with this context’s command. Shorthand for Message.channel.
ok.
it can be a user too, since thats equivalent to Message.channel
nah ctx.send works in dms
oh i read it the other way lmao
I'm talking about ctx.channel.send though
no
They do
ctx.send works on channel
And in dms
ctx.channel in that case would return DMChannel class , and .send() for sure works innit
its ctx.author.send
Lmao "fat chance"
!d discord.ext.commands.Context
class discord.ext.commands.Context(*, message, bot, view, args=..., kwargs=..., prefix=None, command=None, invoked_with=None, invoked_parents=..., invoked_subcommand=None, ...)```
Represents the context in which a command is being invoked under.
This class contains a lot of meta data to help you understand more about the invocation context. This class is not created manually and is instead passed around to commands as the first parameter.
This class implements the [`Messageable`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.Messageable "discord.abc.Messageable") ABC.

No
!d discord.ext.commands.Context.send
await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sends a message to the destination with the content given.
This works similarly to [`send()`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send") for non-interaction contexts.
For interaction based contexts this does one of the following...
yes it works
This is not what i mean
i thought u were saying that if we do ctx.send it sends user msg
I'm talking about ctx.send and ctx.channel.send
channel also has .send()
Hello
I've question
what do i do when i have this?
!d discord.TextChannel.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/master/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/master/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/master/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/master/api.html#discord.Embed "discord.Embed") objects. **Specifying both parameters will lead to an exception**.
I created a channel on a guild using discord.py
and created roles also
how can I make a channel I created (I have its id) to allow only people of certain role to write and read
I tried to set_permissions but I can still see other one without the role using it normally
What version?
uh didnt understand
send_mesage is only really used for Interaction
send_message?
!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.
I've never seen that before
ctx.channel returns a Messageable, why would .send not work on it?
@slate swan it's discord.InteractionResponse.send_message
ok
code?
Interactions are cool af
interactions are painful
import discord
import json
import random
from discord.ext import commands
client = commands.Bot(command_prefix='+')
@client.event
async def on_ready():
print("Ready!")
@client.command()
async def bal(ctx):
a=ctx.author
await open_account(a)
users=await get_bank_data
wallet_amt = users[str(a.id)]["wallet"] = 0
bank_amt = users[str(a.id)]["bank"] = 0
users = get_bank_data()
em = discord.Embed(title=f"{ctx.author.name}'s balance",color=discord.Color.red)
em.add_field(name="Wallet", value=wallet_amt)
em.add_field(name="Bank", value=bank_amt)
await ctx.send(embed=em)
@client.command()
async def beg(ctx):
a=ctx.author
await open_account(ctx.author)
users=await get_bank_data
earnings=random.randrange(250)
await ctx.send(f"Someone gave you {earnings}!")
users[str(a.id)]["wallet"] += earnings
with open("mainbank.json", "w") as f:
users = json.dump(users,f)
async def open_account(a):
users = await get_bank_data()
if str(a.id) in users:
return False
else:
users[str(a.id)] = {}
users[str(a.id)]["wallet"] = 0
with open("mainbank.json", "w") as f:
users = json.dump(users,f)
return True
async def get_bank_data():
with open("mainbank.json", "r") as f:
users = json.load(f)
return users
client.run("TOKEN")```
Don't use this tutorial, it's really bad.
NP
okay
users = await get_bank_data()
and what panda said
sorry for using capital letters just now
What tutorial is that?
one from code with swastik
I also agree but i'm also too lazy to implement them kek
^
😢 this is why i cry at night.
can i do like
async def l(ctx):
await ctx.send("yo")
async def n(ctx):
l(ctx)
Lmaop
Ya
do client = commands.Bot()
ok
But n should be a command and l should be normal function
Adding gasoline to the fire i see
7.3k lmao
This is why we cry
Skids
Contemplating on if i should add my dataclass in my client file or in a utils file 
utils file for more organization
utils file ofc, keep your Client file clean😔
client file if you don't give a shit about organization
Okimii said it's look less clean
Ya that takes time 😔
Since i only have 2 files right now
nah what
okimii himself isnt clean
Lol
i said to have 2 files so another file for the class
I am just making the utils file for that singular dataclass
still
I already have 2 files
shove it in there
then make a third separate file!
I have a single file with single dataclass
i have no dataclasses
More files = clean
^
Is that why i can't navigate through the source code of discord.py and the pyhon bot
just use references no?
https://esolangs.org/wiki/Folders now your speaking my language
Well shit
Guess i am making that file
I rarely navigate, I just type the function name, middle click, my ide takes me to the src 😎
hm
can I like get a user's id with username and discriminator
any help?
yes, sure
!d discord.utils.get
discord.utils.get(iterable, /, **attrs)```
A helper that returns the first element in the iterable that meets all the traits passed in `attrs`. This is an alternative for [`find()`](https://discordpy.readthedocs.io/en/master/api.html#discord.utils.find "discord.utils.find").
When multiple attributes are specified, they are checked using logical AND, not logical OR. Meaning they have to meet every attribute passed in and not one of them.
To have a nested attribute search (i.e. search by `x.y`) then pass in `x__y` as the keyword argument.
If nothing is found that matches the attributes passed, then `None` is returned.
Changed in version 2.0: The `iterable` parameter is now positional-only.
Changed in version 2.0: The `iterable` parameter supports [asynchronous iterable](https://docs.python.org/3/glossary.html#term-asynchronous-iterable "(in Python v3.10)")s...
use this to ger the User object, bot.users would be the iterable, name="name", discriminator="#1234" will be the kwargs
What did you try
calling set_premission on the channel giving it the rule
show the code you have rn?
so the bot shud be in the server for it to work
I meant showing your code
yes sir
That you used to try
okk
Okimii faster
Smh
await channels[0].set_permissions(role, send_messages=False)
channels[0] is the channel I want
and role is the role I want
role is one from guild.roles
that just resets all the settings to default, and turns off send_messages permission, all old configurations get cleared
Atleast they sent a snippet of 1 line of code
how can I make a channel exclusively available for some role?
yo how do i add time as seconds in
sec = 124801284
a = datetime.utcnow()
something like that
you can remove all the perms from the everyone role
Channel.set_permissions(Guild.default_role, view_channel= False)
sec = 124801284
future = datetime.timedelta(seconds=sec)
Just adds the seconds to right now
already tried datetime has no attribute timedelta
then execute the line I added?
did you import datetime from datetime?
yes!
Damn you sarth
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...
I was typing it
lol
Don't steal glory 😔
it exists, surely some import error from your side
i wish i could
it was a auto import issue
ohhm
i thought it was imported
but when i see its something like that
from datetime import date, datetime
;-;
😔 add a , timedelta
and use it directly
no need
Sarth want to see my first api wrapper i'm working on
yes sure, what api does it covers?
A duck one
😳sure
Currently i'm on the phone and is about to sleep in a few
Ducks
tomorrow as in how many hrs? ( my timezone is IST)
Some of it in the python general and hunter
..
Mine is GMT+8 like china's
same
Yea surely ill be online by that time
😔 sad
oh cool
I hate that my school doesn't have a coding class yet everyone else does
1 hour and 30 minutes ahead
What's your time right now
acc to google
Hello Ashley
17:39
Hi Skev
That's
Off-topic channel: #ot2-never-nester’s-nightmare
Please read our off-topic etiquette before participating in conversations.
Cuz army...
You're 1 hour and 30 minutes behind
ye
u sure you're ash? ro someone else in disguise

Yes, its me

Kek
I didn't know if you were referring to yourself or to me
Make a command to control a robot
Attack someone with the robot while on discord
I'd need a robot for that first
Be the first to use discord as a weapon irl
@tasks.loop(seconds=30)
async def logs_dumper(self):
_parent_dir = os.path.abspath(os.getcwd())
with open((_parent_dir + os.sep + "log.txt"), "at") as logs:
logs.writelines(self._temp)
self._temp = []
Would this be alright? It works, I'm just wondering if I should do it asynchronously as well...
lmao
Make a command to make commands for u
game which if youre in a voice channel and you do the command you have a chance to kick yourself from the chat or others
Discord Co-pilot
auto command generator
!pip aiofiles if you wanna do that
Make a command that finds woman suitable for you
uh
guess ill take this 😳
raise NoWomenFound()
Woman detector
ahem ahem
voice stuff with hikari sucks
make a external lib for better support
Thank you!
if isinstance(error, NoWomenFound):
desperate = True
search_for_gay_men()
🤨
Ashley taking the bullet for the women
@slate swan
Uhhhh can we switch the topics?
Oh no brad here
there are already existing ones but they mostly are music related
!pip lavasnek-rs
😩i love this binding
But there's no point of making music bots for me atm
Q/A how mods come here
- Python bot
- Visiting
- a guy told them
ill do it myself😳
Make a akinator type command that can predict what object, or famous person you're thinking about
👌 that would be cool
isnt their an akinator api?
Dunno
there is
lol
i made one with discord.py/disnake
i have seen a dc bot
Sadge
What I can't visit different chats?
!pip akinator.py
I should make a akinator wrapper next
um u can
What channels do you visit often
what do you guys think on
@bot.on_event(GatewayEvent.READY)
async def on_connect() -> None:
print("Ive recieved the READY gateway event!")
?
seems fine, what about other events like member join etc?
Looks
Good?
Yes, good
its psuedo code rn
would it be a single parameters of the event Class, or like discord.py events?
#python-discussion , off topic channels, #discord-bots , staff channels
And help channels
im still working with the gateway because of bad implementations
Of your wrapper?
im sticking by gateway event naming
yes
Oh i'm usually here most of the time but started to go to other channels more often now because of my wrapper
Your wrapper has bad implementations?
thats not what im asking, i was talking about the arguments of the event callback
@bot.on_event(MemberJoin)
async def foo(member : Member):
...
@bot.on_event(MemberJoin)
async def foo(event: MemberJoin):
member = event.member
ive made some bad unorganized impls yes
@tasks.loop(seconds=30)
async def logs_dumper(self):
_parent_dir = os.path.abspath(os.getcwd())
async with aiofiles.open((_parent_dir + os.sep + "log.txt"), "at") as logs:
await logs.write(('\n'.join(self._temp)))
self._temp = []
This works! Thanks again!
But in general, mods get pinged by the bot based on filters for certain words or phrases, or pinged directly, or get a modmail dm that we look into. Outside of that if we are in or visiting a channel and see something out of the ordinary we generally address it
the first one is what discord.py and many other libraries follow
hikari and few libs use the second one
ah, yes they would be called by their entity naming
hm cool
so the 1st one?
that is so.
What are the differences between the two
oh
im so bad i cant even import
in the first one, the event class is just an identification of what it is arguments are being provided to the function seperately and the number of arguments depend on the event
in the second case the class is the event type and acts like a dataclass with all information about that event Stored in it, the event function will always take a single argument event which would be the event class having the data related to the event
but is filtering accurate every time? 😔

in simpler words,
1st one - dpy style
2nd one - hikari style
Yeah, if content in a message matches the filter we get an alert. I don't recall seeing something that accidentally matched the filter. Maybe you have seen a message we should have filtered for?
Imagine a async discord api wrapper that's esoteric
yo help
People in #esoteric-python would definitely use it just to fuck with people
And flex
Suggestion make your discord wrapper esoteric
hm, not yet, seems pretty nice
Imagine it has the best goddamn docs in the world, yet no one can read the src without having a headache
i will not
Sadge
i will be making mine clean and esoteric
😔
😉
fun

this is my code:
intents = discord.Intents.default()
intents.members = True
bot = commands.Bot(command_prefix = bot_prefix, intents = intents)
@bot.event
async def on_member_join(member):
embed = discord.Embed(colour=0x95efcc, description=f"Welcome to Nextvision!", timestamp=datetime.datetime.utcfromtimestamp(1536229094))
embed.set_thumbnail(url="https://cdn.discordapp.com/attachments/933768511145250896/966459729738076180/n7dCH2pmCcaFVWXB.gif")
embed.set_author(name=f"{member.name}", icon_url="https://cdn.discordapp.com/attachments/933768511145250896/966459729738076180/n7dCH2pmCcaFVWXB.gif")
embed.set_footer(text=f"{member.guild}", icon_url="https://cdn.discordapp.com/attachments/933768511145250896/966459729738076180/n7dCH2pmCcaFVWXB.gif")
channel = bot.get_channel(id=962006966086025216)
await channel.send(embed=embed)
I need to do welcome discord bot but its not working and there is no error
If this message sparks a urge to make this a reality in someone please tell me
What is Dis and breakpoint
I removed it now
If
is my task (just dumping logs into a txt file periodically, would it suffice/be wise for me to just do:
@logs_dumper.after_loop
async def on_logs_dumper_cancel(self):
if self.logs_dumper.is_being_cancelled() and len(self._temp != 0):
await self.logs_dumper()
?
But what is it
ok this is the code now
*used to exist https://github.com/b1naryth1ef/disco
I wrote it to do member count
!intents do you have member intents on?
Using intents in discord.py
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default, discord.py has all intents enabled, except for the Members and Presences intents, which are needed for events such as on_member and to get members' statuses.
To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.
Next, in your bot you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:
from discord import Intents
from discord.ext import commands
intents = Intents.default()
intents.members = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see the discord.py docs on intents, and for general information about them, see the Discord developer documentation on intents.
yes
yes, its literally in his code
Oh sorry
I was looking at it pretty much cropped
!d discord.ext.commands.Bot.get_channel
get_channel(id, /)```
Returns a channel or thread with the given ID.
Changed in version 2.0: `id` parameter is now positional-only.
@rain furnace id is positional
Yes, id is positional
where I need to put it?
Just don't make it keyword
remove this line?
What line
.
technically it is fine to specify id when using get_channel
so why its not working
what is the error?
h?
It is?
read tag
Changed in version 2.0: id parameter is now positional-only.
how can i write text to a file without saving it , so tat i can send it via bot?
Uhm d.py get bad every release
no dpy s tier
import datetime
from datetime import datetime,timedelta
what's wrong with using pos arguments, they spare memory cuz id= is like 4 bytes which you'll need in the future 😎
Lol
smort
await message.channel.send('Guess a number between 1 and 10.')
def is_correct(m):
return m.author == message.author and m.content.isdigit()
answer = random.randint(1, 10)
try:
guess = await self.wait_for('message', check=is_correct, timeout=5.0)
except asyncio.TimeoutError:
return await message.channel.send(f'Sorry, you took too long it was {answer}.')
if int(guess.content) == answer:
await message.channel.send('You are right!')
else:
await message.channel.send(f'Oops. It is actually {answer}.')```
Ignoring exception in on_message
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/discord/client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "/Users/bai/Documents/Personal Things/Do not delete/Only viewable by me/Aww Pika Discord Bot/aww pika discord bot.py", line 260, in on_message
guess = await self.wait_for('message', check=is_correct, timeout=5.0)
NameError: name 'self' is not defined
pls help me with this error :/
a = datetime.utcnow()
b = a + datetime.timedelta(seconds=ab)
h?
await bot.wait_for?
;-;
from datetime import datetime
overwrties
import datetime
yes
ok
how to fix
replace self with bot
did u copy the code
it works thx
no i didnt
i wonder why he add self if he didnt copied
it works on my previous python bot script, cuz im rewriting it as a newer way of discord.py
i dont copy codes
@paper sluice
or he was using cogs
?
import datetime
from datetime import datetime as d
async def on_ready(self):
print('Logged on as', self.user)```
this is very old already, my previous script* using discord.Client
irdk
so now im rewriting it*
ya thats fine ig
then that's cog.wait_for
THAT DONT WORK
yeah ik it is
its like very outdated code, so thats why i rewrite, not copy
but it makes sense if u subclass client
>>> import datetime
>>> from datetime import datetime as d
>>> datetime.datetime.now()
datetime.datetime(2022, 4, 21, 18, 23, 39, 406068)
>>> d.now()
datetime.datetime(2022, 4, 21, 18, 23, 42, 573662)
disnake.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: unsupported type for timedelta seconds component: NoneType
why don't u subclass bot too
HI
how code
a = d.utcnow()
b = a + datetime.timedelta(seconds=ab)
<@&831776746206265384>
why did u
One second
late
u cant promo at ot too?
you can't?
ye
They cross posted in 5 channels at once
yeah rule 6
i wonder if mods have power to delete msg or they copy msg id and paste in bot
whats ab?
probably the first
random digits
oh so the python bot doesn't have an anti spam 
they advertise their channel and they havent uploaded since 3 weeks ago
it does
numbers*
it does just not cross channels
It does
ab = await convert2(time1,time2)
understood
it does, just not across channels

It does
>>> a = datetime.timedelta(seconds=173481273)
>>> b = d.utcnow()
>>> b
datetime.datetime(2022, 4, 21, 12, 57, 23, 698695)
>>> a + b
datetime.datetime(2027, 10, 20, 10, 11, 56, 698695)
works fine for me
..
@paper sluice
ig i need to change into int
print and see what it returned
ah so it probably wasnt spam as he didnt really spam messages
Not the one here, but the other channels got zapped
lol none
👏🏻
!e
import datetime
a = datetime.timedelta(seconds=173481273)
b = datetime.datetime.utcnow()
print(b)
c=a+b
print(c)
```ù
@placid skiff :white_check_mark: Your eval job has completed with return code 0.
001 | 2022-04-21 13:04:02.554473
002 | 2027-10-20 10:18:35.554473
it really works lol
cool
Is there a simple method of editing an existing embed's description and nothing else in it?
how do i check if a user has a specific role by id.. ik commands.has_role() exist but is there any other way other than this decorator check?
Probably make a copy of the old embed and then change it's description field. Then, within the same context, do await msg.edit(embed=new_copied_embed)? IDK, I'm just throwing stuff out there
@bot.command()
@commands.has_any_role(692760082085183519, 940008547993927691, 863878825376743475, 902292952381001779, 863879069253894166, 902292952381001779, 863879304110276668, 940008547993927691)
async def пред(ctx, member: discord.Member = None, *, reason = 'Отсутствует'):
print(45)
cursor.execute("""CREATE TABLE IF NOT EXISTS warning(guild_id BIGINT, user_id BIGINT, warn INT, count INT, moderator_id BIGINT, reasons VARCHAR)""")
base.commit()
print(1)
warnings = cursor.execute("SELECT * FROM warning WHERE user_id = ? AND guild_id = ?", (member.id,ctx.guild.id)).fetchone()
print("работает")
if member is None:
await ctx.send("Выберите участника")
return
if warnings is None:
cursor.execute('INSERT INTO warning(guild_id, user_id, warn, count, moderator_id, reasons) VALUES(?, ?, ?, ?, ?, ?)', (ctx.guild.id,member.id,0,1,ctx.author.id,'Отсутствует'))
base.commit()
print(2222)
cursor.execute(f'UPDATE warning SET warn = warn + 1 WHERE user_id = ? AND guild_id = ?', (member.id, ctx.guild.id))
base.commit()
await ctx.send(f"**{ctx.author.name}** Выдал предупреждение #{warnings[2]} {member} (случай # ) {reason}")
else:
cursor.execute(f'UPDATE warning SET warn = warn + 1 WHERE user_id = ? AND guild_id = ?', (member.id, ctx.guild.id))
base.commit()
await ctx.send(f"**{ctx.author.name}** Выдал предупреждение #{warnings[2]} {member} (случай # ) {reason}")
how to make it so that if the reason is not specified, then Отсутствует is not written in the chat?
doesn't it work?
Mm, but how would I read the contents of the old embed with just the message and channel ID?
if the default value is that word it should be working ?
does it raise any error ? or does it send anything ?
I just want to make sure that if there is no reason, Missing is not written in the chat, but if there is, then it is written. I just don't know how to do it..
you paste your code, saying you don't know what to do, but what does the code do
does it work? what does it do? what's the output
What? Can't you see what the code is doing? it issues warnings.
no, you're saying how to make it so that if the reason is not specified, then Отсутствует is not written in the chat?, but as I can see, when your reason isn't speficied the default value is the word you enterered, so I don't see what's not working there
when you run the command what happens
i got stuck for 30 min cuz of indents
damn that hurts
ahem ahem can we be friendly?
ok
sorry()
def foo():
for i in range(10):
if i%2==0:
print(i)
else:
continue
return True
hurts when nothing gets printed 🫂
thanks a lot
i got stuck here
if a2 in d.keys():
if a2 == "w":
if a1 >= 5:
pass
else:
pass
elif a2 == "d":
if a1 >= 30:
pass
else:
pass
......wth is that ew
idk how i didnt see
is it the same code huh
half the things here are useless tbh
async def channelid(ctx):
channel = client.get_channel(channel_id)
await ctx.send(channel)```
why does this not work? i want it to be when command is entered into a channel it sends the channel id, directly in the channel the author had sent it in, how to fix this??
but anyways, im not the one to judge 😔
not sure what do you mean?
lets say i enter the command in this channel
i want the bot to send a message to this channel containing this channel id *
use four spaces
alright, use the channel method on the Context of the command (ctx) which returns a TextChannel object and use the id property on that object in order to gain the channel id
Example
@bot.command()
async def channelid(ctx: commands.Context):
await ctx.send(str(ctx.channel.id))

property not attribute
didnt work
.......?
it didnt send any message to channel
well, error?
no error, it just didnt send
those else?
- did you save the file and rerun the not?
- is it above bot.run() ?
- do you have an on_messave event?
guess what i removed the code
i dont use bot.run()
using start? or well....how are you getting the bot online then
this is how i get my bot online
thats lovely
eye hurting theme
I'm out
?
pika ffs
wat
that string isnt even right😔
go through some tutorials like i told you to
lol wtf
client and bot 2 var
it still works tho
Anyone here have experience with Patreon API?
Is there a way to test without Patreons?
are u using 2 bots?
thats why your commands dont work.
but my other commands works well
idk man mixing up 2 Bot objects will just spoil your code, use a single Bot for your commands
its a multi - purpose bot, thats why need 2 bot objects*
huh? how is that related
nvm
async def math(ctx):
await ctx.send(f"{number} {number2}")
if == number + number2:
await ctx.send('True')``` How do I get the user message in `if` when they answer correct It will reply with "True"
wait_for(event, /, *, check=None, timeout=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Waits for a WebSocket event to be dispatched.
This could be used to wait for a user to reply to a message, or to react to a message, or to edit a message in a self-contained way.
The `timeout` parameter is passed onto [`asyncio.wait_for()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.wait_for "(in Python v3.10)"). By default, it does not timeout. Note that this does propagate the [`asyncio.TimeoutError`](https://docs.python.org/3/library/asyncio-exceptions.html#asyncio.TimeoutError "(in Python v3.10)") for you in case of timeout and is provided for ease of use.
In case the event returns multiple arguments, a [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.10)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/master/api.html#discord-api-events) for a list of events and their parameters.
This function returns the **first event that meets the requirements**...
- where are you getting the
numbervariables from? if ==is invalid syntax- use
wait_formethod
he is trying to explain*
U can implement the arguments as the numbers and type hint with int
But…ur command can either be really basic or complex depending on what ur doing
learn python first
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
how to add reactions to a message ?
Hey @main sonnet!
It looks like you tried to attach a Python file - please use a code-pasting service such as https://paste.pythondiscord.com
a = ctx.send("yo")
a.add_reaction()
@Command
async def uwu(ctx: commands.Context):
msg = await ctx.send("uwu")
await msg.add_reaction("joy") # raw unicode for default emojis
await msg.add_reaction("\1f600") # for default emojis
await msg.add_reaction("\N{THUMBS UP SIGN}") # for default emojis with name
await msg.add_reaction("<:emoji_name:emoji_id>") # for custom emojis (should be present in the server)
whoever that was pls use a pasting service
how to change bot's volume
@slate swan @slate swan in order for something to happen after pressing the reaction, it is necessary that what happens is about how the reaction is called?
How could I make a discord bot with python from scratch?
!d discord.PCMVolumeTransformer
class discord.PCMVolumeTransformer(original, volume=1.0)```
Transforms a previous [`AudioSource`](https://discordpy.readthedocs.io/en/master/api.html#discord.AudioSource "discord.AudioSource") to have volume controls.
This does not work on audio sources that have [`AudioSource.is_opus()`](https://discordpy.readthedocs.io/en/master/api.html#discord.AudioSource.is_opus "discord.AudioSource.is_opus") set to `True`.
@bot.command()
@commands.has_any_role(692760082085183519, 940008547993927691, 863878825376743475, 902292952381001779, 863879069253894166, 902292952381001779, 863879304110276668, 940008547993927691)
async def пред(ctx, member: discord.Member = None, *, reason = 'Отсутствует'):
print(45)
cursor.execute("""CREATE TABLE IF NOT EXISTS warning(guild_id BIGINT, user_id BIGINT, warn INT, count INT, moderator_id BIGINT, reasons VARCHAR)""")
base.commit()
print(1)
warnings = cursor.execute("SELECT * FROM warning WHERE user_id = ? AND guild_id = ?", (member.id,ctx.guild.id)).fetchone()
print("работает")
if member is None:
await ctx.send("Выберите участника")
return
if warnings is None:
cursor.execute('INSERT INTO warning(guild_id, user_id, warn, count, moderator_id, reasons) VALUES(?, ?, ?, ?, ?, ?)', (ctx.guild.id,member.id,0,1,ctx.author.id,'Отсутствует'))
base.commit()
print(2222)
cursor.execute(f'UPDATE warning SET warn = warn + 1 WHERE user_id = ? AND guild_id = ?', (member.id, ctx.guild.id))
base.commit()
await ctx.send(f"**{ctx.author.name}** Выдал предупреждение #{warnings[2]} {member} (случай # ) {reason}")
else:
cursor.execute(f'UPDATE warning SET warn = warn + 1 WHERE user_id = ? AND guild_id = ?', (member.id, ctx.guild.id))
base.commit()
await ctx.send(f"**{ctx.author.name}** Выдал предупреждение #{warnings[2]} {member} (случай # ) {reason}")
how to make it so that if the reason is not specified, then Отсутствует is not written in the chat?
Pasting large amounts of code
If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
!code