#discord-bots
1 messages Β· Page 831 of 1
I got it
It was import datetime not from datetime import datetime
Thanks for all the help @slate swan @maiden fable @quick gust
β€οΈ
Anyone here know how I can find the row number in a sqlite3 table? (I am trying to use this in my bot for a queue function)
wdym fine a row which is the same as an int?
How do I explain this, hmm
Basically, I wanna find the index number of a particular field in a table, if that makes sense.
you want to find a row by the position?
Yea
why exactly and you can get all rows and index
Wait no-
I meant the reverse
I wanna find the position of a row
so users can access your db?
Nonono
Like, the command itself gives the info (the user_id, and some other parameters)
I wanna find the position of any row which has the matching data
sql?
I know how to use the SELECT command
yes
f"SELECT * FROM TABLE WHERE USERID = {ctx.author.id};"
I already know that-
I wanna find the position of it
not sure why youll need the position of a row and not sure if you can
I need to return the position of the user in the queue
ah
well you get all the rows and use .index() which returns the position of the row
async for row in cursor:
row.index(ctx.author.id)
Won't work
It returns a list of tuples, forgot?
π
Remove the message arg
U already got 2 message objects, why u need a third one π
but now I have the error at the bottom
message_before.author.id
o
File "c:\Users\13129\Desktop\Python Bot\Sloth.py", line 69, in on_message_edit
embed=discord.Embed(title=f" edited a message {message_before.member.name}", color=0xffff)
AttributeError: 'Message' object has no attribute 'member'
just got it lol
Hello! I have that command
@bot.event
async def on_member_join(member):
channel = bot.get_channel(942595754613149726)
embed = discord.Embed(title=f"Witamy!", description=f"> Hej! {member.mention} witamy CiΔ na naszym serwerze, mamy nadziejΔ ΕΌe bΔdziesz siΔ dobrze bawiΔ!", timestamp=message.created_at, colour=0xff5252)
embed.set_footer(icon_url="https://cdn.discordapp.com/icons/790998344268513292/c77b0abd957d8d5d1dbed207023886f0.png?size=4096", text="McZone.pl")
await channel.send(embed=embed)
``` on what can i change timestamp=__message__.created_at ?
because this is not async def on_message and i dont have idea
timestamp=datetime.datetime.utcnow()
thank u, i try
Make sure you import datatime
yes yes i know
hey, so i have a discordbot and i want to make a button which can copy a text into the button clickers (so not the host but anybody who can click the button) clipboard
@manic wing thats works, thank u very much
is that possible anyhow or is discord not allowing this?
i dont get what youre trying to do
i have a string and i have a button in discord. anybody on the server can press this button and then i want to paste the text into the the persons clipboard
like i have a message and below this message is a button that says copy and if you click it and press <strg>+v the message from above is there
that was my question. thanks
oh, but i can make it a link and if you press it it asks you to open or copy and then you can copy, can't you?
ups, nope. Doesn't work
hi again
i have that and not works
embed.set_thumbail(url="https://cdn.discordapp.com/icons/790998344268513292/c77b0abd957d8d5d1dbed207023886f0.png")
whats wrong?
ty
hm
set_thumbnail
I mean...we have the same number of eyes
!d discord.TextChannel.set_permissions
await set_permissions(target, *, overwrite=see - below, reason=None, **permissions)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sets the channel specific permission overwrites for a target in the channel.
The `target` parameter should either be a [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") or a [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role") that belongs to guild.
The `overwrite` parameter, if given, must either be `None` or [`PermissionOverwrite`](https://discordpy.readthedocs.io/en/master/api.html#discord.PermissionOverwrite "discord.PermissionOverwrite"). For convenience, you can pass in keyword arguments denoting [`Permissions`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions "discord.Permissions") attributes. If this is done, then you cannot mix the keyword arguments with the `overwrite` parameter.
If the `overwrite` parameter is `None`, then the permission overwrites are deleted.
You must have the [`manage_roles`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") permission to use this...
But better use overwrites param in create_text_channel
!d discord.Guild.create_text_channel
await create_text_channel(name, *, reason=None, category=None, position=..., topic=..., slowmode_delay=..., nsfw=..., overwrites=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Creates a [`TextChannel`](https://discordpy.readthedocs.io/en/master/api.html#discord.TextChannel "discord.TextChannel") for the guild.
Note that you need the [`manage_channels`](https://discordpy.readthedocs.io/en/master/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.9)") of overwrites with the target (either a [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") or a [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role")) as the key and a [`PermissionOverwrite`](https://discordpy.readthedocs.io/en/master/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/master/api.html#discord.TextChannel.edit "discord.TextChannel.edit") will be required to update the position of the channel in the channel list...
how to set thumbnail as user avatar
Just use user.avatar.url
in {} ?
The first argument is Member or Role
never use f string on databases
why
Is this sqlite?
ye
Injections exist
injections?
The thing that automatically formats the argument and puts it into the query
No
Why are you str'ing it
You don't need to
And wrong function
@green bluff so basically
con.execute('INSERT INTO users (id, name) VALUES (?, ?)', (12345, 'good guy'))```
The `?`s will be replaced with arguments you provide in the tuple
```py
"INSERT INTO users (id, name) VALUES (12345, 'good guy')"```

client = commands.Bot(command_prefix=commands.when_mentioned_or('a!'))```
it ain't workin
I would personally make another function that would accept arglist because tuples are crazy inconvenient if you ask me
nor prefix nor after mentionin
can any1 sort it out?
i tried a! and mentionin it but didn't work
await stuff.create_text_channel('the name of channel', overwrites={user: discord.PermissionsOverwrite(send_messages=True, read_messages=True, ...))```
can you help meh with my code
shouldnt the stuff after ?, ? be f string
client = commands.Bot(command_prefix=commands.when_mentioned_or('a!'))```
any1?
!d sqlite3.Cursor.execute
execute(sql[, parameters])```
Executes an SQL statement. Values may be bound to the statement using [placeholders](https://docs.python.org/3/library/sqlite3.html#sqlite3-placeholders).
[`execute()`](https://docs.python.org/3/library/sqlite3.html#sqlite3.Cursor.execute "sqlite3.Cursor.execute") will only execute a single SQL statement. If you try to execute more than one statement with it, it will raise a [`Warning`](https://docs.python.org/3/library/sqlite3.html#sqlite3.Warning "sqlite3.Warning"). Use [`executescript()`](https://docs.python.org/3/library/sqlite3.html#sqlite3.Cursor.executescript "sqlite3.Cursor.executescript") if you want to execute multiple SQL statements with one call.
no such thing
as when mentioned
i got it in disnake library
even with disnake that literally makes no sense
What
Try putting it into a separated function, not sure why this doesn't work tho
!d disnake.ext.commands.when_mentioned_or
disnake.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://docs.disnake.dev/en/latest/ext/commands/api.html#disnake.ext.commands.Bot.command_prefix "disnake.ext.commands.Bot.command_prefix") attribute.
Example
```py
bot = commands.Bot(command_prefix=commands.when_mentioned_or('!'))
```...
see my code correct but still
Define not work
No reacting to anything?
Woah woah
Don't
https://vcokltfre.dev check this out
A tutorial on how to use discord.py to create your own Discord bot in Python, written to fix the flaws of many other popular tutorials.
That's very uh not good
yeah
Don't watch that tutorial
well none of my command respond to it
Probably outdated or done by a stupid person
or both
when i mention it or trigger command with prefix
Check the one I sent above
wait
Outdated
@client.command()
Check this out @languid wagon
Properly you don't even define it as Client
It should be Bot
Not really
I too prefer client
Bot is a subclass of client
I mean you can call the variable whatever you like, but it should be commands.Bot
The Bot is the subclass of Client and implements some functionality
Check docs for both classes and compare them
oh so its better
Yeah
how to define "Context" ?
async def hello(ctx):
bruh
It is passed as first attribute of command func
its like self in classes
aa easy lang pls
i just started py
Like im doin py for a week
You should get intermediate python knowledge first
I learnt, kick,ban and slash command
just use (ctx, yourargs) with your def's if its a command
Cause it's an advanced async application that requires a decent knowledge
im tryin prefix mention bot thingy
i still have no idea how async and await work lol
lol
people like the async-await ability tho i guess
@bot.command()
async def command(ctx: commands.Context, arg1, arg2, ...):
ctx <- is context```
!blocking
Why do we need asynchronous programming?
Imagine that you're coding a Discord bot and every time somebody uses a command, you need to get some information from a database. But there's a catch: the database servers are acting up today and take a whole 10 seconds to respond. If you do not use asynchronous methods, your whole bot will stop running until it gets a response from the database. How do you fix this? Asynchronous programming.
What is asynchronous programming?
An asynchronous program utilises the async and await keywords. An asynchronous program pauses what it's doing and does something else whilst it waits for some third-party service to complete whatever it's supposed to do. Any code within an async context manager or function marked with the await keyword indicates to Python, that whilst this operation is being completed, it can do something else. For example:
import discord
# Bunch of bot code
async def ping(ctx):
await ctx.send("Pong!")
What does the term "blocking" mean?
A blocking operation is wherever you do something without awaiting it. This tells Python that this step must be completed before it can do anything else. Common examples of blocking operations, as simple as they may seem, include: outputting text, adding two numbers and appending an item onto a list. Most common Python libraries have an asynchronous version available to use in asynchronous contexts.
async libraries
The standard async library - asyncio
Asynchronous web requests - aiohttp
Talking to PostgreSQL asynchronously - asyncpg
MongoDB interactions asynchronously - motor
Check out this list for even more!
do you need to specify it as commands.Context?
ty @vale wing
I usually typehint literally everything for code editing convenience
who here knows wavelink?
commands.Context worked
does this mean it will run lets say a different command?
No thanks
https://wavelink.readthedocs.io/en/1.0/exts/spotify.html
trying to use spotify support in wavelink music sys but cant figure out that which attribute to use in track? for example in yt it was
@commands.command()
async def play(self, ctx: commands.Context, *, track: wavelink.YoutubeTrack:
print(track)```
in spotify which it wud be?
`track: spotify.Spotify...?`

Against ToS
i want bot find message and add reaction on that, when someone click same reaction bot add role someone have idea?
cuz if it continues the same function it might break, right?
who said? wavelink isnt against tos?
It streams from Youtube/Spotify without their permission, so yes
lavalink
i am not using youtube track of wavelink?
nice edit
which lib shud i use then
!d discord.on_reaction_add probably is what you need
discord.on_reaction_add(reaction, user)```
Called when a message has a reaction added to it. Similar to [`on_message_edit()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_message_edit "discord.on_message_edit"), if the message is not found in the internal message cache, then this event will not be called. Consider using [`on_raw_reaction_add()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_raw_reaction_add "discord.on_raw_reaction_add") instead.
Note
To get the [`Message`](https://discordpy.readthedocs.io/en/master/api.html#discord.Message "discord.Message") being reacted, access it via [`Reaction.message`](https://discordpy.readthedocs.io/en/master/api.html#discord.Reaction.message "discord.Reaction.message").
This requires [`Intents.reactions`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.reactions "discord.Intents.reactions") to be enabled.
Note
This doesnβt require [`Intents.members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.members "discord.Intents.members") within a guild context, but due to Discord not providing updated user information in a direct message itβs required for direct messages to receive this event. Consider using [`on_raw_reaction_add()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_raw_reaction_add "discord.on_raw_reaction_add") if you need this and do not otherwise want to enable the members intent.
oh so no f string
you don't use any
but bot must find message with id
for them
@green bluff yeah read that doc
isnt f string just easier
gg
Just clarified myself more
what's the way to send a message from the api?
asyncio
Wym
Wym
.send() i guess
oh
Lol
Integrate your service with Discord β whether it's a bot or a game or whatever your wildest imagination can come up with.
its aiohttp
so basically "use await if you want other stuff to run while waiting for a response from 3rd party stuff", so like a response from discord in that case
As for SQLite it is probably ok as there are not many types, and you would only need to add quotes around strings, but when it comes to more complicated databases with more complicated types (like postgres), the injections are way more convenient
does it run the rest of the function?
The standard is to use injections and not the f strings
or just different ones then
This is more like #databases question
easier, sure. But sanitising your queries is better
Hi, I have if i have an issue with code error for discord dashboard is this the right channel or do i have to go to #web-development ?
@green bluff but you may check this https://www.sqlite.org/lang_delete.html
lol
if the error is related to the webserver part then #web-development would be more useful yeah
ok well it aint
!d discord.Permissions
class discord.Permissions(permissions=0, **kwargs)```
Wraps up the Discord permission value.
The properties provided are two way. You can set and retrieve individual bits using the properties as if they were regular bools. This allows you to edit permissions.
Changed in version 1.3: You can now use keyword arguments to initialize [`Permissions`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions "discord.Permissions") similar to [`update()`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.update "discord.Permissions.update").
do you have a file called discord.py?
nope this is for my discord dashboard
@jade tartan print discord.__version__
from quart import Quart, render_template, redirect, url_for
from quart_discord import DiscordOAuth2Session, requires_authorization, Unauthorized
from nextcord.ext import ipc
import nextcord
app = Quart(__name__)
app.secret_key =
print(os.environ["OAUTHLIB_INSECURE_TRANSPORT"]) == "true"
app.config["DISCORD_CLIENT_ID"] =
app.config["DISCORD_CLIENT_SECRET"] = ""
app.config["DISCORD_REDIRECT_URI"] = ""
app.config["DISCORD_BOT_TOKEN"] = ""
discord = DiscordOAuth2Session(app)
@app.route("/login/")
async def login():
return await discord.create_sessions()
@app.route("/callback/")
async def callback():
try:
await discord.callback()
except:
return redirect(url_for("login"))
return redirect(url_for("dashboard"))
I have never use quart_discord
its from this vid https://www.youtube.com/watch?v=Pq96MJKArHc&ab_channel=Glowstik
Hey!
Thanks for watching todays video, todays video I really hope you enjoyed and join my discorddd :) Also thank you SO MUCH for 1370 subscribers!!
LINKS -
Join my Discord - https://discord.gg/twHW4UUJGq
Nextcord Server - https://discord.gg/Ucmae5Kbwb
Set Up VSC - https://www.youtube.com/watch?v=KpzkP...
Set Up PYTHON - https://youtu.be/h4...
So?
so I can't help you with this
@vale wing ^^
!d discord.Client.wait_for
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.9)"). 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.9)") 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.9)") 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**...
you can use this to wait for a reaction, then send a message
i did but it wont work hehe
can you send what you tried?
why is there a message parameter?
your check needs to check if user == ctx.author
message is a str
you indo?
ngehh
You need to set the read_messages to False for guild.default_role
welp
And could you like read the docs
Why message arg
You should learn how to get info from docs
I gave you 2 links
!d discord.TextChannel.set_permissions
await set_permissions(target, *, overwrite=see - below, reason=None, **permissions)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sets the channel specific permission overwrites for a target in the channel.
The `target` parameter should either be a [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") or a [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role") that belongs to guild.
The `overwrite` parameter, if given, must either be `None` or [`PermissionOverwrite`](https://discordpy.readthedocs.io/en/master/api.html#discord.PermissionOverwrite "discord.PermissionOverwrite"). For convenience, you can pass in keyword arguments denoting [`Permissions`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions "discord.Permissions") attributes. If this is done, then you cannot mix the keyword arguments with the `overwrite` parameter.
If the `overwrite` parameter is `None`, then the permission overwrites are deleted.
You must have the [`manage_roles`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") permission to use this...
@bot.command(aliases=["rec"])
async def recruit(message):
await channel.send('react to this message')
def check(reaction, user):
return user == message.author and str(reaction.emoji) == 'π'
try:
reaction, user = await bot.wait_for('reaction_add', timeout=60.0, check=check)
except asyncio.TimeoutError:
await channel.send('π')
else:
await channel.send('π')```
!d discord.Guild.create_text_channel
await create_text_channel(name, *, reason=None, category=None, position=..., topic=..., slowmode_delay=..., nsfw=..., overwrites=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Creates a [`TextChannel`](https://discordpy.readthedocs.io/en/master/api.html#discord.TextChannel "discord.TextChannel") for the guild.
Note that you need the [`manage_channels`](https://discordpy.readthedocs.io/en/master/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.9)") of overwrites with the target (either a [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") or a [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role")) as the key and a [`PermissionOverwrite`](https://discordpy.readthedocs.io/en/master/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/master/api.html#discord.TextChannel.edit "discord.TextChannel.edit") will be required to update the position of the channel in the channel list...
Um
The ctx should be the first argument
messy
And you access message by ctx.message
async def recruit(ctx):
await ctx.send('react to this message')
def check(reaction, user):
return user == message.author and str(reaction.emoji) == ':thumbsup:'
try:
reaction, user = await bot.wait_for('reaction_add', timeout=60.0, check=check)
except asyncio.TimeoutError:
await ctx.send(':thumbsdown:')
else:
await ctx.send(':thumbsup:')```
like this?
im confused now 
You need to change the check function now
Im here
As you don't have message defined
!code
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
It should be ctx.message
For better understanding u can use this
Look in the docs what you need to parse to there
overwrite.permissions = True also u can use
What is that
Yeah
See the power of docs
this?
πΏ
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.
Method
You can provide it as a key to your dict
interaction.user: discord.PermissionOverwrite(read_messages=True)``` ex
Just get the role object
!d discord.Guild.get_role
get_role(role_id, /)```
Returns a role with the given ID.
you need ctx
Hello can anyone link me to a good tutorial on how to make discord bots with cogs and classes, thank you.
go search making discord.py bots
Not the actual type
they have series
And you get that object from Guild.get_role
A tutorial on how to use discord.py to create your own Discord bot in Python, written to fix the flaws of many other popular tutorials.
@bot.command(aliases=["rec"])
async def recruit(ctx):
await ctx.channel.send('react to this message')
def check(reaction, user):
return user == ctx.message.author and str(reaction.emoji) == 'π'
try:
reaction, user = await bot.wait_for('reaction_add', timeout=60.0, check=check)
except asyncio.TimeoutError:
await ctx.channel.send('π')
else:
await ctx.channel.send('π')
This works if thats what you are looking for
Isn't this like outdated, like aren't there a bunch of d.py forks?
Very large percent of them is outdated or misinformated
this is what i want to make
Most of features this tutorial covers didn't change
The forks add features and not remove them mostly
Official discord.py not supported anymore tho right?
Yes
Ook ok thanks
You can learn forks after you learn base why not
but the bot not yet add reaction
yeah yeah
mind if you add me as friends?
you want the bot to add a reaction to the message?
yea
i feel good helping you here
most of the forks are similar to discord.py but they just have new features
just like this
i used to use discord.py but i wanted timeouts so i switched to nextcord
k
And Guild must be an object as well
@bot.command(aliases=["rec"])
async def recruit(ctx):
message = await ctx.channel.send('react to this message')
await message.add_reaction('π')
await message.add_reaction('π')
def check(reaction, user):
return user == ctx.message.author and str(reaction.emoji) == 'π'
try:
reaction, user = await bot.wait_for('reaction_add', timeout=60.0, check=check)
except asyncio.TimeoutError:
await ctx.channel.send('π')
else:
await ctx.channel.send('π')
``` Now it adds reactions to the message, when you press π it responds with π
May I ask what is your python knowledge
What is timeout for
Then don't start learning python from making discord bot
It is complicated for beginners
it gives the user 60 seconds if he wants to react
Can we delete it?
well idk whats gonna happen if you do im not that good
ill try for you thogh
I see
File "c:\Users\hp\Desktop\bot\logs.py", line 18, in on_message_delete
embed.set_author(name=f"{message.author}", icon_url=f"{message.author.avatar.url}")
AttributeError: 'NoneType' object has no attribute 'url'
how message.author not working
bro may i ask what is the code for delete the bots msg?
!d delete_after
{message.author.avatar_url}
....?
..
disnake
the msg of the bot
lemee show u code
message.author.display_avatar.url
Use that instead of .avatar
@commands.Cog.listener()
async def on_message_delete(self, message):
embed = disnake.Embed(description=f"**Message Sent by {message.author.mention} Deleted in** <#{message.channel.id}> \n Message : {message.content}",color=aqua,timestamp=datetime.utcnow())
embed.set_author(name=f"{message.author}", icon_url=f"{message.author.avatar.url}")
await channelslogs.send(embed=embed)
If the user has a default avatar then .avatar will return None
yes i have default avatar lol
There's a delete_after kwarg
and um what is the reactor called, example who run the command is author.
default avatar
@nimble plume
There's a difference in what I'm telling you to use and what you're already using
can you give me the docs?
ok
!d discord.Messageable.send
No documentation found for the requested symbol.
!d discord.ext.commands.Context.send
await send(content=None, *, tts=None, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, mention_author=None, view=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.9)") 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.9)") of [`Embed`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed "discord.Embed") objects. **Specifying both parameters will lead to an exception**.
There
.avatar -> .display_avatar
Thanks it works
Yw
and um the react thing
and server avatar?
F
{user.mention}
not user.name?
its only the name and not ping i think
you have to think about some other things too
for example:
how long do you want the bot to reply when someone reacts?
...
I made delete_after=60
So after a minute right
good maths
@bot.listen()
async def on_message_delete(message):
embed=discord.Embed(description=f"{} deleted a message".format(message.author.name) color=0)
embed.add_field(name= message.content ,value="This is the message that he has deleted", inline=True)
channel=bot.get_channel(943385924052602880)
await channel.send(channel, embed=embed)```error:
``` File "main.py", line 34
embed=discord.Embed(description=f"{} deleted a message".format(message.author.name) color=0)
^
SyntaxError: invalid syntax```
a comma
embed=discord.Embed(description=f"{} deleted a message".format(message.author.name), color=0)
^
SyntaxError: f-string: empty expression not allowed```
just do f"{message.author.name} deleted a message"
you should know what f strings are by now, I've seen you here before
shit_times = "daily"
print(f"I shit {shit_times}")
# is the same as
print("I shit {}".format(shit_times))```
ah yes i remember u
code looks familiar
ah yes
I'm here after a very long time.
async def f(ctx):
message = await ctx.channel.send("F kawan kawan:Empe_MafuSad:", delete_after=60)
await message.add_reaction('π«')
def check(reaction, user):
return user == ctx.message.author and str(reaction.emoji) == 'π«'
try:
reaction, user = await bot.wait_for('reaction_add', timeout=60.0, check=check)
except asyncio.TimeoutError:
await ctx.channel.send('f banget')
else:
await ctx.channel.send('π«, Respect by {}'format(user.name))
```
Format(user.name)
I cannot use it :)
you don't need to use it
think about what you're doing in your code pls
it only does it once, you don't have a while loop
you're waiting for ONE reaction, then the waiting is done
@bot.command()
async def f(ctx):
message = await ctx.channel.send("F kawan kawan:Empe_MafuSad:", delete_after=60)
await message.add_reaction(':regional_indicator_f:')
def check(reaction, user):
return user == ctx.message.author and str(reaction.emoji) == ':regional_indicator_f:'
try:
reaction, user = await bot.wait_for('reaction_add', timeout=60.0, check=check)
except asyncio.TimeoutError:
await ctx.channel.send('f banget')
else:
while True:
await ctx.channel.send(':regional_indicator_f:, Respect by {}'.format(user.name))```
like this?
ofc not
you have to while loop the whole wait_for stuff
think first, then code
I also highly suggest you to clear the reactions after the timeout is over
it's guild.default_role
how to get display avatar of guild
icon_url if you're on v1.7.3
if the server has no avatar
if serrver has no icon
then you'd just notify the user I'd say
try and see
?
well, what's the use of displaying a default avatar if there isn't one?
it gives error
ofc it does
yes and it cant send
error says it all, no?
async def button_callback(interaction):
new_text_channel = await interaction.guild.create_text_channel(str(interaction.user))
await new_text_channel.set_permissions(interaction.guild.default_role, view_channel=False)```
the channel name is pretty bad imo, since it can cause issues, like idk for sure if a # can be in a channelname
ofc, your bigbrain set view_channel to False
you can do the following:
voice channel limit ?
nope
overwrites = {
guild.default_role: discord.PermissionOverwrite(view_channel = False),
interaction invoker: discord.PermissionOverwrite(view_channel = True),
guild.me: discord.PermissionOverwrite(view_channel = True)}
await interaction.guild.create_text_channel(name=..., overwrites=overwrites)
this is obviously not something to simply copy paste, you need to edit some stuff
you'll see...
name is ...
interaction invoker
...
guild is probably undefined too, ...
yeah, your indentation is off, that's why you don't copy paste
I love your code indents
just type it out, you can't make mistakes that way
you'll also LEARN what you coded, instead of just copy pasting
Use a code formatter
also, make sure you know what you typed
for example
I doubt you know what guild.me is or why I put it there
help me guys
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
Remove the py
ok
oh
google that error, it's VERY common
python -m pip
python -m pip install discord.py
buzzer
Discord is a mirror package
Oh ok
you have to replace that with the user who clicked the button ofc
try and see
yup, now it's just interaction.guild instead of just guild π§
**interaction.**guild
last line needs to also be IN the function
cur.execute("INSERT INTO members WHERE id = ?", inter.author.id)
you know how to do this without python? show me first
plain SQL
well, show me
a 1 line example
of how you would insert
not what I asked tho
you do, as you mentioned
What are you trying to ask...
hi nova
Who you
what're your columns in "members" and what exactly do you want to add in the existing row?
do you want some way of doing it without sql queries?
no, he just wants to add data to an existing member, based on its ID
UPDATE
then not UPDATE
you want EVERY row to have the same columns, you DON'T want some rows to not have certain columns while others do in the same table
you have to rethink your data model
I suggest to use an extra table for the verification stuff
so table VERIFICATION has an ID, ...
@grim oar can u help me
No
ok
can you help me @vocal snow
No
ok
@grim oar can u show me how to run shards in seperate threads
No lol
ok
lmao
@bot.command()
async def top(ctx):
users = []
async with ctx.typing():
lb = discord.Embed(title="leaderboard", description="top salcash players", color=ctx.author.color)
l = database.length()
for i in range (int(l)):
s = database.get(i)
user = await bot.fetch_user(s)
level = database.check_level(s)
o = user.display_name
users.append((o, level))
users.sort(key=lambda a: a[1], reverse=True)
leaderboard = map(lambda user: user[0] + " level: " + str(user[1]), users)
g = list(leaderboard)
ln = len(g)
for i in range (ln):
lb.add_field(name=i+1, value=g[i], inline=False)
await ctx.send(embed=lb)```
tf wrong
nothing's really wrong, it's more a warning
aand
TypeError: 'coroutine' object is not iterable
there's more to that error
but it most likely means you forgot an await somewhere
Ignoring exception in on_command_error
Traceback (most recent call last):
File "C:\Python310\lib\site-packages\discord\ext\commands\core.py", line 167, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Users\User\Downloads\PycharmProjects\main.py\main.py", line 1224, in top
g = list(leaderboard)
TypeError: 'coroutine' object is not iterable
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Python310\lib\site-packages\discord\client.py", line 351, in _run_event
await coro(*args, **kwargs)
File "C:\Users\User\Downloads\PycharmProjects\main.py\main.py", line 117, in on_command_error
raise error
File "C:\Python310\lib\site-packages\discord\ext\commands\bot.py", line 994, in invoke
await ctx.command.invoke(ctx)
File "C:\Python310\lib\site-packages\discord\ext\commands\core.py", line 894, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Python310\lib\site-packages\discord\ext\commands\core.py", line 176, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: 'coroutine' object is not iterable```
print leaderboard, it's probably not what you think
mm ok
?
what
<coroutine object Command.__call__ at 0x000001E13886CF20>
C:\Python310\lib\site-packages\discord\ext\commands\core.py:167: RuntimeWarning: coroutine 'Command.__call__' was never awaited
ret = await coro(*args, **kwargs)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback```
!rule 6 thanks
error says it all, you have to read it
Have you re defined map
i await where
the VERIFICATION table should in relation with the members table
check every variable
mm ok
since you probably want to "add extra columns" when he's verified or whatever
instead you only add stuff in the extra table if the user is verified
well, what's your goal?
that's insert into <table name>
now be concrete pls
example:
if a user verified, I want to change the verified column from False to True and add ...
hear me out: why don't you just only add users once they're verified? what's the use of adding users that aren't verified?
what's the use of storing an unverified user?
hmm alright, so now, isn't it a bit more useful to only store verified users? since unverified users don't really have an extra value to the db
how do i get the missing role from commands.Missing role
I'm asking you these questions so you SEE why it would be useless to store unverified users when they don't contain useful info...
what useful data does an unverified user have?
in the long run, you could have thousands of AFK accounts in your db, because they joined once and are now just catching dust
still...
which is?
so just nothing actually
my thought process
if user not in DB => unverified
stil not found da one that needed to be awaited
have you printed every single variable and verified it's correct / what you need?
well, i need leaderboard
that's why the members table should contain 2 columns:
guild_id user_id
have you printed every single variable and verified it's correct
dk about lambda and map
and sort
are you sure a map is iterable and the elements in the map are not coroutines (so they're awaited)?
@bot.command()
async def top(ctx):
users = []
async with ctx.typing():
lb = discord.Embed(title="leaderboard", description="top salcash players", color=ctx.author.color)
l = database.length()
for i in range (int(l)):
s = database.get(i)
user = await bot.fetch_user(s)
level = database.check_level(s)
o = user.display_name
users.append((o, level))
users.sort(key=lambda a: a[1], reverse=True)
leaderboard = map(lambda user: user[0] + " level: " + str(user[1]), users)
print(leaderboard)```
i...dk?
you're not even using the level variable?
how do i do
download python
ofc, you only execute db commands when the user is in the server? I don't get your point
i have a emty list
else not going??
if ctx.author.id == ownvc[0]:
does leaderboard correctly print?
what
my list is empty thats why it said index out of range
there, u answer ur own question
ig
i wan solution
what? add item??
if this if didnt work go to else statement but it gives error and stop
should i use try except?
and can you iterate through a map? as asked previously
idk about that
what r u trying to do
channel10 = something
channel10 = channel10
will it work?
and why variable reloaded??
reload the varaible
well, if you were able to, you should not list()
ok
"channel10" = "channel10" will work
string??? whyy
what
but in da prog i dont even use list()
??
*list.append(item)
ok?
nope, "=" is to set value, and u cant do the sec one
if to True and False, use comparator "=="
what r u even trying to do
ok, now what
you do
list(leaderboard)
i comment it?
seems fine, as long as the interaction.user refers to the user who clicked the button
what happens when you print leaderboard tho?
<coroutine object Command.call at 0x000001E13886CF20>
C:\Python310\lib\site-packages\discord\ext\commands\core.py:167: RuntimeWarning: coroutine 'Command.call' was never awaited
ret = await coro(*args, **kwargs)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
yes i want to set value
seems like you have to await some function you forgot, but what function π¬
ok, just use
varName = "value" or True or False or 1
I already told you the fix for that
if ctx.author.id == ownvc[0]:
s = disnake.Embed(title=f"U Already own a private voice channel",color=red,timestamp=datetime.utcnow())
await ctx.reply(embed=s)
elif not channel1:
```else not going it says index out of range
we have to see some error traceback my guy
ownvc probably isn't what you think it is
the list is empty
no, guild = interaction.guild
- the error is in that top command
- i see no problem except ofc, DAT WARING KINDA THING
show me the code once again, I'll do a quick rewrite
@bot.command()
async def top(ctx):
users = []
async with ctx.typing():
lb = discord.Embed(title="leaderboard", description="top salcash players", color=ctx.author.color)
l = database.length()
for i in range (int(l)):
s = database.get(i)
user = await bot.fetch_user(s)
level = database.check_level(s)
o = user.display_name
users.append((o, level))
users.sort(key=lambda a: a[1], reverse=True)
leaderboard = map(lambda user: user[0] + " level: " + str(user[1]), users)
print(leaderboard)
# g = list(leaderboard)
# ln = len(g)
# for i in range (ln):
# lb.add_field(name=i+1, value=g[i], inline=False)
# await ctx.send(embed=lb)``` ignore comment
what's s? print it for me and show the result
def get(index):
cur.execute("SELECT NAME FROM users_data LIMIT 1 OFFSET ?",(index,))
n = cur.fetchone()
return n[0]``` from database
disnake.ext.commands.errors.CommandInvokeError: Command raised an exception: IndexError: list index out of range
just do
print(f"{s}, {type(s)}")```
add item bruh
you have a TRACEBACK, there's more than one line
what code i should comment
just put that line under s = ...
k
What is the output of print(leaderboard)
yes i want the if statement to goto else
if the list is empty
map returns a map object
Have you re defined map function
maybe check for the list at first
if not <shit_list>:
lol
I am unable to use gear emoji β in my button when I put it it look like this instead β
please help
@nextcord.ui.button(
label="β",style=nextcord.ButtonStyle.green, custom_id="help_setup", row=0
)
async def help_setup(
self, button: nextcord.ui.Button, interaction: nextcord.Interaction
):
await Help.handle_click(self, button, interaction)
nextcord.
this works in the code my guy, don't worry about it
but you have better notationsl
yes.
use this instead
"\U00002699"
I'll completely ignore the fact that it may be me since that name is not mine
emoji
@nextcord.ui.button(
label="\U00002699",style=nextcord.ButtonStyle.green, custom_id="help_setup", row=0
)
async def help_setup(
self, button: nextcord.ui.Button, interaction: nextcord.Interaction
):
await Help.handle_click(self, button, interaction)```
same result for me
cool buttons
strange, maybe not supported
it is but idk how
this is some other bot
what is it ?
this guy i mean
oh , then how do I use custom emoji
Use emoji kwarg, not label
!ephemeral
but it not the same on still
it's a kwarg in the send method, you have to set it to True
.
eh wasnt there a tag
pass an Emoji Or partial emoji
wdym ?
pass an emoji or partialemoji object
do I need download that as an custom emoji ?
What?
@potent spear
762854807068344321, <class 'str'>
752729024442138673, <class 'str'>
840224507036696616, <class 'str'>
695337807782215771, <class 'str'>
786157376213352458, <class 'str'>
886120777630486538, <class 'str'>
761187678287953920, <class 'str'>
628604207402057760, <class 'str'>
906520975951142912, <class 'str'>
879000165757890570, <class 'str'>
406955601881727007, <class 'str'>
592545312837468170, <class 'str'>
902373236849922078, <class 'str'>
873085052655927336, <class 'str'>
676829520980082718, <class 'str'>
858874474639523850, <class 'str'>
210177401064390658, <class 'str'>
879159531232452678, <class 'str'>
C:\Python310\lib\site-packages\discord\ext\commands\core.py:167: RuntimeWarning: coroutine 'Command.__call__' was never awaited
ret = await coro(*args, **kwargs)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
<coroutine object Command.__call__ at 0x000001E36146CEB0>```
What u searching for
ephemeral = True if u wondering how to use
!d discord.InteractionResponse.send_message
await send_message(content=None, *, embed=..., embeds=..., view=..., tts=False, ephemeral=False)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Responds to this interaction by sending a message.
There (:
interaction.response.send_message
Istg why dpy broke the naming convention
How do I make button like first image
its a custom emoji prolly
!d discord.ButtonStyle.grey
ok, it is what I thought it was, you know what get_user does, right?
in what
show your code again
@bot.command()
async def top(ctx):
users = []
async with ctx.typing():
lb = discord.Embed(title="leaderboard", description="top salcash players", color=ctx.author.color)
l = database.length()
for i in range (int(l)):
s = database.get(i)
user = await bot.fetch_user(s)
level = database.check_level(s)
o = user.display_name
users.append((o, level))
users.sort(key=lambda a: a[1], reverse=True)
leaderboard = map(lambda user: user[0] + " level: " + str(user[1]), users)
print(leaderboard)
# g = list(leaderboard)
# ln = len(g)
# for i in range (ln):
# lb.add_field(name=i+1, value=g[i], inline=False)
# await ctx.send(embed=lb)
i mean the emoji
I mean fetch_user, in your case
mm, kinda know
Those are just custom emojis ig? Idrk
ok, get user object
aight, by ID, right?
yep
well, then why are you passing a STRING?
?
oh, ok, then what does it affect
what lib are you using? I'll doublecheck
discord?
not dpy probably
@small igloo :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | ModuleNotFoundError: No module named 'discord'
πΏ
ded
nextcord? what are you using...
πΏ π
what??
bruh, your python discord package, which one is it?
how to check
you don't know?
dpy?
have you ever checked documentation?
thats wut i mean, how to chec
irrelevant for now, where do you learn what methods an object has etc?
like how do you know that member has a .id attribute etc, what website do you use?
yt and self learn
YT, really?
yep
so you've never used the docs?
once xd
ok, sometimes w3
that's for python, you don't find stuff for libraries on there
tell me the website at least
yt, w3,
, and replit discussion
none of them are official documentation
π€¦ββοΈ
ik :v
and still you just proceeded?
yep :)
you know why we can answer all your questions right? because we read the docs
sometimes doc not help for me-
some goes for people who answer on stackoverflow etc
that's because you don't know how to use them
litteraly π π π
you know python right? or is this your first python project? :/
hi hay
hi
ik, why
hi Im very confused
I have this code but it doesnt send the embed
@commands.command()
@commands.has_permissions(administrator=True)
async def rules(self, ctx):
with open('prefixes.json', 'r') as f:
prefixes = json.load(f)
print(
f'{datetime.now()}: {ctx.message.author} executed command - {prefixes[str(ctx.guild.id)]}{ctx.invoked_with}')
server_id = ctx.message.guild.id
if discord.utils.get(ctx.guild.text_channels, name="rules"):
channel = discord.utils.get(ctx.guild.channels, name="rules")
rules_id = channel.id
print(rules_id)
print(f'Channel #RulesΒ΄already exist in server, server ID: {server_id}')
print(f"Sending Rules.Embed to #Rules \n Channel ID: {rules_id}")
ascii_banner = pyfiglet.figlet_format("RULES & INFORMATION")
rules_embed = discord.Embed(title=ascii_banner,
description="Welcome to Eivee's Community Discord server")
await bot.get_channel(rules_id).send(embed=rules_embed)
else:
create_channel = await ctx.guild.create_text_channel('rules')
print(create_channel.id)
is it not await bot.get_channel(channel-id).send(embed=your-embed) or did I do something wrong?
since I'll use terms which are understandable if you know programming terms
ok
just split it in 2 lines
channel = bot.get_channel(...)
await channel.send(...)```
@small igloo would you please change your nickname so that it abides by our #rules (i.e. doesn't have cusses or other profanities in it)
ops ok srry
but I tried that also, I just got the same error
show me first
also, this is terrible
if discord.utils.get(ctx.guild.text_channels, name="rules"):
channel = discord.utils.get(ctx.guild.channels, name="rules")```
you know why, right?
Thanks π
np
how do I use custom emji in button?
ok pep8
It's discord.ext.commands.Bot
why is that bad?
just emoji = "<:emojiname:emojiid>"
you don't need them anymore, have you finally used the emoji kwarg instead of label?
you're doing the same thing twice...
oh yeaa, I get that
and?
today, you'll learn how to use the docs instead of reddit and stackoverflow
never use reddit xd
if you're using python 3.9+ you can use a walrus operator
else, you have an alternative
I completely feel the frustration
mmmmm
I did as u told me and still got this
YT is like reading a book's summary, you'll only know what the summary tells you and you have no idea about the details
especially the parts which YOU need to implements, since there's no way you need an exact copy of what the guy on yt tells you
is that replit
show me your imports
I keep forgetting about walrus operator, I have never really used it before
ok, chpter 2, what does dat says
same I forgot it exists π
that says to check the docs
i never know that walrus operation exist π
ok, you have to import Bot, not bot
ooohh, was it for real just that......
depends
Who in the world imports the Bot class...
right
just 2 chapters with 54 words? what book is that, i wanna buy
just
from discord.ext import commands
me 
you can drop all what's underneath from imports
frr cant relate
It's a kid's book
I'll have a stroke now
lol ok
import discord
import discord.utils
``` 
When Iβm subclassing I like just having the name
l i n k
not commands.
use your google skills
demn ok
keyword
show me your imports first
"Library" docs
k ty
I'll cry if you search "Library" docs on google
grab your tissues
I'll simply leave to save the pain
ill better give it a default value???/
lol
Unnecessary but fine
im confused else
None or empty will both result in True
ye but im using [0]
ok, now what thing i should click first
woah
oh fuc
and? you were asking for "how to check if a list is empty"
light
okok
fish + duck
im blind
I dont have my glasses, i cant read small text
hi blind, i'm dad!
You're being unnecessarily difficult
its blur u cant read it with glasses
mmm, GG
blue***
lul
blur*
why u fix the right word
Lol;I still cant anyways
Correct
my monitor resolution is low then π
ok, what should i click first https://docs.python.org/3/library/
Oh fuck, you searched library docs
Ahhhhhhh
hey, i searched python library docs
Idk if I should laugh or cry
It's Bot, not bot
!resources Β―_(γ)_/Β―
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
crlaugh
aight
it didnt fix it and I tried a few different things but still not working, and there is this error now complaining about the id
define id variable
!d discord.ext.commands.Bot.get_channel
get_channel(id, /)```
Returns a channel or thread with the given ID.
again, what should i click first
If you cant help, dont try to help
If you don't want help then leave
da hec my fault
ok
Learn how to read errors, you are missing a postional argument when you call the method.
You're being unnecessarily difficult
i ask not help :)
Oh God
but I dont understand what Im doing wrong, I changed the code a little bit from last time. it looks like this now and in my eyes I think it should be working
@commands.command()
@commands.has_permissions(administrator=True)
async def rules(self, ctx):
with open('prefixes.json', 'r') as f:
prefixes = json.load(f)
print(
f'{datetime.now()}: {ctx.message.author} executed command - {prefixes[str(ctx.guild.id)]}{ctx.invoked_with}')
server_id = ctx.message.guild.id
if channeli := discord.utils.get(ctx.guild.text_channels, name="rules"):
id = channeli.id
print(channeli.id)
channel = Bot.get_channel(id)
print(f'Channel #RulesΒ΄already exist in server, server ID: {server_id}')
print(f"Sending Rules.Embed to #Rules \n Channel ID: {id}")
ascii_banner = pyfiglet.figlet_format("RULES & INFORMATION")
rules_embed = discord.Embed(title="ascii_banner",
description="Welcome to Eivee's Community Discord server")
await channel.send(embed=rules_embed)
else:
create_channel = await ctx.guild.create_text_channel('rules')
print(create_channel.id)
i just fking need answer to fix
ret = await coro(*args, **kwargs)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
<coroutine object Command.__call__ at 0x000001E36146CEB0>``` :')
You didn't await something
@bot.command()
async def top(ctx):
users = []
async with ctx.typing():
lb = discord.Embed(title="leaderboard", description="top salcash players", color=ctx.author.color)
l = database.length()
for i in range (int(l)):
s = database.get(i)
print(f"{s}, {type(s)}")
user = await bot.fetch_user(s)
level = database.check_level(s)
o = user.display_name
users.append((o, level))
users.sort(key=lambda a: a[1], reverse=True)
leaderboard = map(lambda user: user[0] + " level: " + str(user[1]), users)
print(leaderboard)
# g = list(leaderboard)
# ln = len(g)
# for i in range (ln):
# lb.add_field(name=i+1, value=g[i], inline=False)
# await ctx.send(embed=lb)```
oh god
if ctx.author.id == ownvc:
Show full error
thats the full error
also ```py
ownvc.append(ctx.author.id)
Are your methods to fetch data from your database not async?
@commands.guild_only()
@commands.command(name="prvoice")
async def prvoice(self , ctx, arg=None , arg2=None, arg3=None):
ownvc = []
vclist = ["PRVC-1","PRVC-2","PRVC-3","PRVC-4","PRVC-5","PRVC-6","PRVC-7","PRVC-8","PRVC-9","PRVC-10"]
overwrite = disnake.PermissionOverwrite()
overwrite.connect = False
overwrite2 = disnake.PermissionOverwrite()
overwrite2.connect = True
category = ctx.channel.category
channel1 = disnake.utils.get(ctx.guild.voice_channels, name='PRVC-1')
channel2 = disnake.utils.get(ctx.guild.voice_channels, name='PRVC-2')
channel3 = disnake.utils.get(ctx.guild.voice_channels, name='PRVC-3')
channel4 = disnake.utils.get(ctx.guild.voice_channels, name='PRVC-4')
channel5 = disnake.utils.get(ctx.guild.voice_channels, name='PRVC-5')
channel6 = disnake.utils.get(ctx.guild.voice_channels, name='PRVC-6')
channel7 = disnake.utils.get(ctx.guild.voice_channels, name='PRVC-7')
channel8 = disnake.utils.get(ctx.guild.voice_channels, name='PRVC-8')
channel9 = disnake.utils.get(ctx.guild.voice_channels, name='PRVC-9')
channel10 = disnake.utils.get(ctx.guild.voice_channels, name='PRVC-10')
if arg == "create":
if ctx.author.id == ownvc:
s = disnake.Embed(title=f"U Already own a private voice channel",color=red,timestamp=datetime.utcnow())
await ctx.reply(embed=s)
elif not channel1:
await ctx.guild.create_voice_channel("PRVC-1", category=category)
ownvc.append(ctx.author.id)
```help?
waht
dk if u also need the print(s) and type
762854807068344321, <class 'str'>
752729024442138673, <class 'str'>
840224507036696616, <class 'str'>
695337807782215771, <class 'str'>
786157376213352458, <class 'str'>
886120777630486538, <class 'str'>
761187678287953920, <class 'str'>
628604207402057760, <class 'str'>
906520975951142912, <class 'str'>
879000165757890570, <class 'str'>
406955601881727007, <class 'str'>
592545312837468170, <class 'str'>
902373236849922078, <class 'str'>
873085052655927336, <class 'str'>
676829520980082718, <class 'str'>
858874474639523850, <class 'str'>
210177401064390658, <class 'str'>
879159531232452678, <class 'str'>
C:\Python310\lib\site-packages\discord\ext\commands\core.py:167: RuntimeWarning: coroutine 'Command.__call__' was never awaited
ret = await coro(*args, **kwargs)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
<coroutine object Command.__call__ at 0x000001E36146CEB0>```
await
It tells you the issue and @boreal ravine said alread
and idk where to add dat await E
whats database
file name
What?
lol
umm, nope ig?
what
Why do we need asynchronous programming?
Imagine that you're coding a Discord bot and every time somebody uses a command, you need to get some information from a database. But there's a catch: the database servers are acting up today and take a whole 10 seconds to respond. If you do not use asynchronous methods, your whole bot will stop running until it gets a response from the database. How do you fix this? Asynchronous programming.
What is asynchronous programming?
An asynchronous program utilises the async and await keywords. An asynchronous program pauses what it's doing and does something else whilst it waits for some third-party service to complete whatever it's supposed to do. Any code within an async context manager or function marked with the await keyword indicates to Python, that whilst this operation is being completed, it can do something else. For example:
import discord
# Bunch of bot code
async def ping(ctx):
await ctx.send("Pong!")
What does the term "blocking" mean?
A blocking operation is wherever you do something without awaiting it. This tells Python that this step must be completed before it can do anything else. Common examples of blocking operations, as simple as they may seem, include: outputting text, adding two numbers and appending an item onto a list. Most common Python libraries have an asynchronous version available to use in asynchronous contexts.
async libraries
The standard async library - asyncio
Asynchronous web requests - aiohttp
Talking to PostgreSQL asynchronously - asyncpg
MongoDB interactions asynchronously - motor
Check out this list for even more!
I still dont know if I should cry or laugh or bang my head in a wall
crlabang
I think you should evacuate
Sweet
Why are you guys being rude
h
WE are being rude
1m years BC we still onga bonga
Fush literally wasted 15 minutes because they didnt await a coro
Like wth
and idk where to ad dat fking await reeeee
Dude, they obviously don't know what to await
how to check if the item is in list
.
use the in operator
ok if item in list:
yes
uwu_list = ["hunter"]
if "hunter" in uwu_list: return "uwu"```
who can explain me how to work with json and mapping?
Not here.
i just realised ur pfp is diff
ownvc.append(ctx.author.id)
```not working??
i need it for discordpy
same
camelCase should never be used in python. The convention is to use snake_case for variable and function names. Therefore userID would become user_id
Define "not working"
Doesn't matter, ask somewhere else
not adding author id in list
def notWorking():
#code ig
lol
rude
lowercase w
mm, yep
Your if statements are never true, thats why
elif not channel1:
await ctx.guild.create_voice_channel("PRVC-1", category=category)
channel1 = disnake.utils.get(ctx.guild.voice_channels, name='PRVC-1')
await channel1.set_permissions(ctx.guild.default_role, overwrite=overwrite)
await channel1.set_permissions(ctx.author, overwrite=overwrite2)
ownvc.append(ctx.author.id)
s = disnake.Embed(title="Created a Private voice PRVC-1",description="use : `!prvoice modify`",color=green,timestamp=datetime.utcnow())
await ctx.reply(embed=s)
```its sending msg + creating a channel
elif type == "address":
try:
for i in range (0, len(Json_Items)):
for x in Json_Items[i]:
for c in Json_Items[i][x]:
if (','.join(Json_Items[i][x]["P A"])) == str(id):
if finished == False:
print("hello")
finished = True
break
else:
# invalid = discord.Embed(title="Cosmic Overground Check", description="You have entered an **invalid** payment address, you have either entered a ``user p a`` that doesn't exist or ``user a` not in our data base", color = discord.Color.red())
# await ctx.send(embed=invalid)
print("bye")
finished = True
yo why does "bye" never run?, I need to so if they enter a invalid P A, it prints the bye statement once
indents
still wait for answer...
they all are correct
yes
I have no idea, maybe ask in the d.py server
nope
ok
i just changed it in disocrd
ded ok
all indents are correct
the elif statement is never true.
bruh, u ned some tabs
just joking around with him dw
I need it to print (bye) once, right now it prints it for every time of the loop
elif type == "address":
try:
for i in range (0, len(Json_Items)):
for x in Json_Items[i]:
for c in Json_Items[i][x]:
if (','.join(Json_Items[i][x]["Payment Address"])) == str(id):
if finished == False:
print("hello")
finished = True
break
else:
# invalid = discord.Embed(title="Cosmic Overground Check", description="You have entered an **invalid** payment address, you have either entered a ``user payment address`` that doesn't exist or ``user payment address`` not in our data base", color = discord.Color.red())
# await ctx.send(embed=invalid)
print("bye")
finished = True```
never true.
ok
yes?
who send the msg then? @boreal ravine
in what language of the world does never true means i didnt understand
im confused thats why i cant understand
If he is saying your if statement is never true he means it never results in a true value
ok
for example ||if i wronmg correct me|| if 1>2 #blablabla
channel1 = disnake.utils.get(ctx.guild.voice_channels, name='PRVC-1')
elif not channel1:
await ctx.guild.create_voice_channel("PRVC-1", category=category)
channel1 = disnake.utils.get(ctx.guild.voice_channels, name='PRVC-1')
await channel1.set_permissions(ctx.guild.default_role, overwrite=overwrite)
await channel1.set_permissions(ctx.author, overwrite=overwrite2)
ownvc.append(ctx.author.id)
s = disnake.Embed(title="Created a Private voice PRVC-1",description="use : `!prvoice modify`",color=green,timestamp=datetime.utcnow())
await ctx.reply(embed=s)
ok
disnake
yes
hikari&rinlover suggested me
literally the best fork
at least its good, corresponding to a fork
ok
@slate swan
whats the issue?
no i added it after disnake
what do you mean?
wdym by that
is everything before append working?
yes even it send the message ctx.reply*
How do you know appending isn't working?
is there a position arg for button
i printed the list
wait
very very weird thing happened
disnake.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'set_permissions'
elif not channel4:
await ctx.guild.create_voice_channel("PRVC-4", category=category)
channel4 = disnake.utils.get(ctx.guild.voice_channels, name='PRVC-4')
await channel4.set_permissions(ctx.guild.default_role, overwrite=overwrite)
await channel4.set_permissions(ctx.author, overwrite=overwrite2)
ownvc.append(ctx.author.id)
s = disnake.Embed(title="Created a Private voice PRVC-4",description="use : `!prvoice modify`",color=green,timestamp=datetime.utcnow())
await ctx.reply(embed=s)
your channel4 is returning None
it creates a channel but
if you are creating a channel then store the create method in a variable
how?
channel = await discord.Guild.create_voice_channel(name="uwu")
await channel.set_permissions()
channel4 = disnake.utils.get(ctx.guild.voice_channels, name='PRVC-4')

confuse