#discord-bots
1 messages · Page 138 of 1
You said that man
where?
Ok thank you I will ask another one
alright
There are a lot of videos on youtube that can help you with what you are looking for @hushed ridge
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
!d discord.Member.ban
await ban(*, delete_message_days=..., delete_message_seconds=..., reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Bans this member. Equivalent to [`Guild.ban()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild.ban "discord.Guild.ban").
help()``````py
help(request)```
Invoke the built-in help system. (This function is intended for interactive use.) If no argument is given, the interactive help system starts on the interpreter console. If the argument is a string, then the string is looked up as the name of a module, function, class, method, keyword, or documentation topic, and a help page is printed on the console. If the argument is any other kind of object, a help page on the object is generated.
Note that if a slash(/) appears in the parameter list of a function when invoking [`help()`](https://docs.python.org/3/library/functions.html#help "help"), it means that the parameters prior to the slash are positional-only. For more info, see [the FAQ entry on positional-only parameters](https://docs.python.org/3/faq/programming.html#faq-positional-only-arguments).
This function is added to the built-in namespace by the [`site`](https://docs.python.org/3/library/site.html#module-site "site: Module responsible for site-specific configuration.") module.
youtube tutorials are either outdated or awfully bad
but you can use it if you learn from it
Not all of them
There are some good videos out there if you know how to look
@client.event
async def on_message( message ):
if message.author.bot:
return
else:
member = message.author.name
msg_len = len(message.content)
rand_number_1 = randint( 1, 10 )
exp_first = msg_len * rand_number_1
coins_first = exp_first // 10
data_levels_member_first = { 'exp': 0, 'coins': 0, 'level': 0}
filename = f'./Data/Profiles/Profile{message.author.name}{message.guild}.json'
try:
data = load( filename )
except Exception:
dump( filename, data_levels_member_first )
data = load( filename )
exp_member = data['exp']
coins_member = data['coins']
lvl_member = data['level']
exp = exp_first + exp_member
coins = coins_first + coins_member
lvl = exp ** (1/4)
if lvl_member < lvl:
lvl_member += 1
print('You lvl up!')
data_levels_member = { 'exp': exp, 'coins': coins, 'level': lvl_member}
dump( filename, data_levels_member )
await client.process_commands(message)
this code is right? for leveling system bot
Please anyone tell me.
if you want to learn how to make a discord bot, you should first learn python, get some experience on async and OOP, view the documentation, and see examples on the temporarily inexistent repo
don't use json as a database
Fix it.
that's not my problem nor my job
Bro ur aren't a good helper bruh
I'm not a helper, I'm a volunteer spending valuable time trying to help people with problems that they might have with their code. Not giving them copy-paste solutions
Run it and see ™️
How do you wanna learn if you're asking us to just give you the answers?
As he already said, we're not here to just give you the code, but to help and direct you to where you can learn about it
hey robin
hello
says
;-;?
this problem always happens
@client.event
async def on_member_join(member):
with open('users.json', 'r') as f:
users = json.load(f)
await update_data(users, member)
with open('users.json', 'w') as f:
json.dump(users, f)
the problem is here
What's before it?
Hey @hushed ridge!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
someone send me all basic commands log call log entry etc
@client.event
async def on_message( message ):
if message.author.bot:
return
else:
member = message.author.name
msg_len = len(message.content)
rand_number_1 = randint( 1, 10 )
exp_first = msg_len * rand_number_1
coins_first = exp_first // 10
data_levels_member_first = { 'exp': 0, 'coins': 0, 'level': 0}
filename = f'./Data/Profiles/Profile{message.author.name}{message.guild}.json'
try:
data = load( filename )
except Exception:
dump( filename, data_levels_member_first )
data = load( filename )
exp_member = data['exp']
coins_member = data['coins']
lvl_member = data['level']
exp = exp_first + exp_member
coins = coins_first + coins_member
lvl = exp ** (1/4)
if lvl_member < lvl:
lvl_member += 1
print('You lvl up!')
data_levels_member = { 'exp': exp, 'coins': coins, 'level': lvl_member}
dump( filename, data_levels_member )
await client.process_commands(message)
import json
import discord
try:
with open("users.json") as fp:
users = json.load(fp)
except Exception:
users = {}
def save_users():
with open("users.json", "w+") as fp:
json.dump(users, fp, sort_keys=True, indent=4)
def add_points(user: discord.User, points: int):
id = user.id
if id not in users:
users[id] = {}
users[id]["points"] = users[id].get("points", 0) + points
print("{} now has {} points".format(user.name, users[id]["points"]))
save_users()
def get_points(user: discord.User):
id = user.id
if id in users:
return users[id].get("points", 0)
return 0
@client.event
async def on_message(message):
if message.author == client.user:
return
print("{} sent a message".format(message.author.name))
if message.content.lower().startswith("!lvl"):
msg = "You have {} points!".format(get_points(message.author))
await client.process_commands(message.channel, msg)
add_points(message.author, 1)
client.run(token)
quick question, it has been a long time since I have messed around with discord bot dev, but the github repo for the discord.py library doesn't exist anymore, so i'm not really sure what library is recommended to use
why does this not work UNBAN ALL
async def unbanall(ctx):
count = 0
banned_users = await ctx.guild.bans()
for ban_entry in banned_users:
user = ban_entry.user
await ctx.guild.unban(user)
count += 1
await ctx.channel.send(f"unbanned {count}")```
danny got shadow banned. Read more here: <#381965829857738772 message> (make sure you've joined the dpy server)
Guild.bans is an async iterator as of 2.0
!d discord.Guild.bans
async for ... in bans(*, limit=1000, before=..., after=...)```
Retrieves an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator "(in Python v3.11)") of the users that are banned from the guild as a [`BanEntry`](https://discordpy.readthedocs.io/en/latest/api.html#discord.BanEntry "discord.BanEntry").
You must have [`ban_members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.ban_members "discord.Permissions.ban_members") to get this information.
Changed in version 2.0: Due to a breaking change in Discord’s API, this now returns a paginated iterator instead of a list.
Examples
Usage...
there're some examples in the docs
wait did this just happen the day I decided to get back into bot dev? anyway tysm
apparently so lol, it happened earlier today
if you still want to install dpy, you can use the stable pypi version
alright thanks :)
no
;-;
Wtf? 330Billion??
Who is that crazy would write this? xD
NO WAY!
Google Is 2000Billion line
,_, 2Trillion wtf? xd
Facebook is 60Mil lol xd
GTA V is 30 Mil wow xd
discord.py still exists
I don't understand how lines of code means anything
The owner has just been accidentally "shadowbanned" - it should be back shortly
i own this record but I used only print statements so gg
;-;
Hello fellow users of discord.py I need help!
So I have it where someone inputs the !stage command and then their stage... It sends a message in another where the FTO will react to the message and when reacted they will get a DM with info! As you can in the lines that have **<----- with the Capital words I need this info from the stage command but I am not smart enough to figure it out! Please someone with big brain help me ^^^^
EX: I need to get the person that originally send the !stage 1 command for the THIS PERSON part
for the RIDE ALONG part I need to get the stage that they put ( Stage being the number in !stage 3)
async def stage(ctx, *, stage):
ftochannel = client.get_channel(1043289756794093639)
logchannel = client.get_channel(1037550844935147622)
embed=discord.Embed(title=f"{ctx.author.mention} has requested ride along for stage **{stage}**",description=f"If you want to assist this member with their requested stage react below!", color=0x660066)
log=discord.Embed(title=f"Discord Log // User Requested Ride Along in BCSO Discord",description=f'Ran By: {ctx.author.mention}\nActual Command Finish: {ctx.author.mention} has just requested the following stage: {stage}! ',color=0x660066)
emoji = "\N{Large Yellow Circle}"
msg = await ftochannel.send(embed=embed)
await msg.add_reaction(emoji)
await ctx.send("When an FTO member answers me You will get a message from me with more information! Please be patient!")
await logchannel.send(embed=log)```
async def on_raw_reaction_add(payload):
if str(payload.emoji) == "\N{Large Yellow Circle}":
member = payload.member
sendEmbedToUser = discord.Embed(title=f'Hello!', description=f'You have accepted **THIS PERSONS<---** Stage **RIDE ALONG!<---**\nPlease Arrive in [#1038926472259313732](/guild/267624335836053506/channel/1038926472259313732/) within **10 Minutes**!\n\nHere is some helpful documentation for your ride along:\n[LINK SHORTNER 1]\n[LINK SHORTNER 1]\n[LINK SHORTNER 1]\n[LINK SHORTNER 1]
await member.send(embed=sendEmbedToUser)```
Any way to check if the user is on 2 devices
No
I have a guy testing bugs and almost all my commands are broken because a user can just use them at the same time on 2 devices and they'll both go through
Even though I have cooldowns, I guess the write to the database isn't fast enough
Any way to like, delay processed commands until a previous one has finished?
Broken how?
What you're looking for is to use a wait_for within the stage command
uhmmmm
Where would I actually put that?
Broken as in like I have a command the gives the user some money. It has a 6 hour cooldown. If a user on 2 different devices uses the command at the same time on each device, they get twice the money
After the message saying "react to this message", since that's when you want to wait for a message
Can you show your code?
I suppose
not really possible but there's a small workaround
you can track different statuses on mobile, web and desktop client
https://discordpy.readthedocs.io/en/stable/api.html#discord.Member.desktop_status
https://discordpy.readthedocs.io/en/stable/api.html#discord.Member.web_status
https://discordpy.readthedocs.io/en/stable/api.html#discord.Member.mobile_status
That would cover if a user was on a desktop and a phone, but not 2 desktops, right?
nope
Not sure if multiple of those properties can be true at once
it also wont cover up if the user has sync settings on
a status always has to return a value, if not applicable it will just return offline
So like await msg.add_reaction(emoji) would be client.wait_for msg.add_reaction(emoji)?
!d discord.Client.wait_for see here for documentation and an example
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.11)"). 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.11)") 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.11)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/latest/api.html#discord-api-events) for a list of events and their parameters.
This function returns the **first event that meets the requirements**...
it says removeGiftcard(‘10dollar.txt), how do i make the value of ‘10dollar.txt’ be logged onto a webhook when it is removed
@miner.tree.command(name='account', description='View yours a friends account!')
@app_commands.describe(user = 'Who?')
async def account(interaction: discord.Interaction, user: str=''):
id = interaction.user
with open("users.json", "r") as f:
users = json.load(f)
try:
bitcoin = users[f'{id.id}']['bitcoin']
await interaction.response.send_message(bitcoin)
except:
msg = await interaction.response.send_message("You dont have an account! Making one now!")
with open("users.json", "r") as f:
users = json.load(f)
await upd(users, id)
with open("users.json", "w") as f:
json.dump(users, f, indent=4)
asyncio.sleep(2)
await interaction.response.edit(content=f"{id.mention} Made an account!")
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/runner/crypto-miner-bot/venv/lib/python3.8/site-packages/discord/app_commands/tree.py", line 1242, in _call
await command._invoke_with_namespace(interaction, namespace)
File "/home/runner/crypto-miner-bot/venv/lib/python3.8/site-packages/discord/app_commands/commands.py", line 887, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
File "/home/runner/crypto-miner-bot/venv/lib/python3.8/site-packages/discord/app_commands/commands.py", line 880, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'account' raised an exception: AttributeError: 'InteractionResponse' object has no attribute 'edit'
@commands.command()
@commands.cooldown(1, 1, commands.BucketType.user)
async def test2(self, ctx):
try:
await ctx.send('1')
async with connection.cursor() as cursor:
await cursor.fetch("SELECT part_id, part_name FROM parts ORDER BY part_name")
rows = cur.fetchall()
await ctx.send('2')
await ctx.send(rows)
except Exception as e:
print(e)
```how do i define connection in this case
how can I edit a slash command message
await interaction.response.edit(content=f"{id.mention} Made an account!") this thing here is wrong
it doesnt exist
ive tried looking at the docs and I still dont have it
!d discord.InteractionResponse
class discord.InteractionResponse```
Represents a Discord interaction response.
This type can be accessed through [`Interaction.response`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction.response "discord.Interaction.response").
New in version 2.0.
@slate swan try reading this
that is what im reading
you fix that?
?
db connect
yea im still having trouble with this
I'm jumping back into a bot I made a few years ago, looks like there's been some big updates. Can anyone recommend a walkthrough video that'll catch me up on the basics?
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/runner/crypto-miner-bot/venv/lib/python3.8/site-packages/discord/app_commands/tree.py", line 1242, in _call
await command._invoke_with_namespace(interaction, namespace)
File "/home/runner/crypto-miner-bot/venv/lib/python3.8/site-packages/discord/app_commands/commands.py", line 887, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
File "/home/runner/crypto-miner-bot/venv/lib/python3.8/site-packages/discord/app_commands/commands.py", line 880, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'account' raised an exception: InteractionResponded: This interaction has already been responded to before
await interaction.response.edit_message(content=f"{id.mention} Made an account!")
A lot of the videos are out of date and aren't that good. I'd recommend the official migration guide documentation: https://discordpy.readthedocs.io/en/stable/migrating.html
Thanks Robin! That's exactly what I need.
no worries
you already responded the interaction.
@commands.command()
@commands.cooldown(1, 1, commands.BucketType.user)
async def test2(self, ctx):
try:
await ctx.send('1')
async with connection.cursor() as cursor:
await cursor.fetch("SELECT part_id, part_name FROM parts ORDER BY part_name")
rows = cur.fetchall()
await ctx.send('2')
await ctx.send(rows)
except Exception as e:
print(e)
```how do i define connection in this case
async with aiosqlite.connect('database.db') as db:
async with db.execute("SELECT part_id, part_name FROM parts ORDER BY part_name") as cursor:
rows = cur.fetchall()
im using pgsql
read the pgsql document then 😛
yea im trying to edit the message i send
huh
where it says removeGiftcard(‘10dollar.txt), how do i make the value of ‘10dollar.txt’ be logged onto a webhook when it is removed
define the message and then use .edit method
!d discord.Message.edit
await edit(*, content=..., embed=..., embeds=..., attachments=..., suppress=False, delete_after=None, allowed_mentions=..., view=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Edits the message.
The content must be able to be transformed into a string via `str(content)`.
Changed in version 1.3: The `suppress` keyword-only parameter was added.
Changed in version 2.0: Edits are no longer in-place, the newly edited message is returned instead.
Changed in version 2.0: This function will now raise [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "(in Python v3.11)") instead of `InvalidArgument`.
i got rate limited on railway.app 💀
You got ratelimited on replit v2
Anybody worked with aiomysql before?
Uh has danny been kicked from github or something? 👀
lol
its from the discord.py srv
he basically got shadowbanned
stuff is still there though, they are working on recovering it
railway.app gets rate limited very frequently also?
Can i apply tasks.loop inside the normal chat trigger callback?
like update channel name thing
`def run_discord_bot():
intents = discord.Intents.default()
intents.message_content = True
client = discord.Client(intents=intents)
bot = commands.Bot(command_prefix='!', intents=intents)
@bot.command()
async def new_user(ctx, target, real_name=None):
print("AHHHHHH")
db = db_connect.DB()
db.insert_user(target, real_name)`
Is there any obvious reason why my new_user command wouldnt be triggering at all? no errors, no feedback from the print statement
why can't we have custom colors on our buttons
that would literally be so damn nice
are you calling bot.run?
client.run(TOKEN)
yeah its at the bottom, below a bunch of commented out stuff, didnt want to bog down the post with it
Not the client
o
Are you running the bot instance
Anyways there's no reason to have both a client and bot
bot is just an extension of client
`bot = commands.Bot(command_prefix='!', intents=intents)
@bot.command()`
isn't that these 2 lines?
oo maybe thats it then
Where are you calling bot.run is my question
Because if you aren't running it then your commands won't work
o interesting. so my client and bot do the same thing?
Bot is Client with the command extension
so if im wanting to do commands, i should just use bot?
Yes
ok awesome. ill make that change, and hopefully you wont hear back from me about this
will mean you fixed it, thanks!
File "/home/container/.local/lib/python3.10/site-packages/discord/app_commands/tree.py", line 1242, in _call
await command._invoke_with_namespace(interaction, namespace)
File "/home/container/.local/lib/python3.10/site-packages/discord/app_commands/commands.py", line 887, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
File "/home/container/.local/lib/python3.10/site-packages/discord/app_commands/commands.py", line 880, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'redeem' raised an exception: AttributeError: 'Interaction' object has no attribute 'add_roles'```
.user.add_roles
thanks
result is None
Who muted me bro
and ı have a question how to make only owner command
!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.
@slate swan
@lavish micamands.isowner()
thanks
yep
code:
https://paste.pythondiscord.com/paseyevone
when im doing the disable/enable command it says:
https://paste.pythondiscord.com/beferuzaze
Converting to "int" failed for parameter "pep_number".
is not working is it have a video?
verifed bot??????
problem error install: pip install discord.py -
have 100 server lol.
Try reading the error, Not just the last few lines either
It tells you exactly what's missing and where to install it
gpooooooood
there pip install discord.py
???
but install sigh
explain differents pip vs pip3
sigh ok moment
You shouldn't be using either, use the py launcher (py -m pip ...)
py -m pip ..?
but my little first time.
What?
pip install discord.py not just pip discord.py
Do this first
Yes
okay moment try.
You'll still get the same error
..I already said. Read the error
upgrade your pip
Why??
already ya have version actual.
explain there "error" there red
????
it tells you
you would know if you read it
I've even told you it's in the first screenshot
sigh think is "pip install pyproject-toml"?
yeah but no idea much and my little english
i am no good english
There's a very detailed sentence that even includes a link
click the build tools link and download it
Background
I was about to try Python package downloaded from GitHub, and realized that it did not have a setup.py, so I could not install it with
pip install -e <folder>
Instead, the package...
already same.
Wdym ah did you not see that

thanks @upbeat gust ok
and different pip vs pip3
or pip (any 1 , 2 and 3) no?
thre commands "pip3"
on linux, pip is used to install packages for python2 and pip3 for python3
Ahh
i see only pip right?
not linux pip3
It doesn't even matter, just use py -m pip
py -m pip install discord right?
ok thanks memory..
only owner is not working
@slvl.command()
@commands.has_permissions(administrator=True)
async def enable(ctx):
async with bot.db.cursor() as cursor:
await cursor.execute("SELECT levelsys FROM levelSettings WHERE guild = ?", (ctx.guild.id,))
levelsys = await cursor.fetchone()
if levelsys:
if levelsys[0]:
return await ctx.send("The leveling system is already enabled! ")
await cursor.execute("UPDATE levelSettings SET levelsys = ? WHERE guild = ?", (True, ctx.guild.id,))
else:
await cursor.execute("INSERT INTO levelSettings VALUES (?, ?, ?, ?, ?), PRIMARY KEY (guild, user)", (True, 0, 0, 0, ctx.guild.id,))
await ctx.send("Enabled the leveling system")
await bot.db.commit()
its part of the database schema
not the insert
Yes
that doesnt worj
RIMARY
OH
do i do that outside
yes i will
nextcord.ext.commands.errors.CommandInvokeError: Command raised an exception: IntegrityError: UNIQUE constraint failed: levelSettings.id
same error
how do I find the role of a member and give them a role if they don't have it?
what's " the role of a member"
?
first of all u cant have two primary keys
second unique here failed coz somewhere u tried to insert a row with same key again
so check ur insert statements
Basic SQLite moment 
its full of mistakes whats integerp and u didn't even declare data type for primary key at this point u are just adding stuff in a sentence and praying it works
how to make only command on python is_owner is not working
What
What?
What is not working
Please elaborate on your problem instead of just saying "not working?" Provide a full traceback or an error report, otherwise we won't be able to help.
yes
nopee
wait
@tree.command(name='gen', description='generate keys')
@commands.is_owner()
async def redeem(interaction: discord.Interaction, amount: int):```
I made a generate and redeem command
but is not wokring
@commands.is_owner()
async def redeem(interaction: discord.Interaction, amount: int):
key_amt = range(int(amount))
f = open("keys.txt", "a")
show_key = ''
for x in key_amt:
key = str(uuid.uuid4())
show_key += "\n" + key
f.write(key)
f.write("\n")
if len(str(show_key)) == 37:
show_key = show_key.replace('\n', '')
await interaction.response.send_message(f"**{show_key}**")
return 0
if len(str(show_key)) > 37:
await interaction.response.send_message(f"**{show_key}**")
else:
await interaction.response.send_message(":negative_squared_cross_mark:")```
because commands.is_owner is for message commands
why are you even using slash for an owner only command
everyone will see
bro i need help
hi,
I am trying to make buttons and have this code. I don't understand why it isn't working.
class yesNoMenu(discord.ui.View):
def __init__(self):
super().__init__()
@discord.ui.button(label = "yes", style=discord.ButtonStyle.green)
async def yes_butn(self, button: discord.ui.Button, interaction: discord.Interaction):
await interaction.response.send_message("yes")
@discord.ui.button(label="no", style=discord.ButtonStyle.red)
async def yes_butn(self, button: discord.ui.Button, interaction: discord.Interaction):
await interaction.response.send_message("no")
@client.tree.command(name="test")
async def test(interaction: discord.Interaction, person: discord.Member):
view = yesNoMenu()
await interaction.response.send_message("Yes or no?", view=view)
For some reason, it's adding only 1 button, but not both.
i solved the intents glitch
but when i run the code in replit it gives another error
i need some on to collaborate with me
Change one of them
The method names are duplicated
this is code link
oh, wow. Thank you. Thats stupid
please help
Paste it somewhere else, why would people make an account just to view the code
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.
bro the thing i need to show you is the error
Then copy the error and send it
you still havent shown the error
Is there any documentation and/or quickstarts out there for discord.py's slash command features?
I don't see anything in the site, could just have overlooked it though
oop nevermind, the gist in the pins seems to cover it nicely
ashley ftw
discord.py maintainers were also working on an official guide idk whats the progress tho
how do i display a user’s pfp in an embedded message with a python code
!d discord.User.avatar for the pfp
property avatar```
Returns an [`Asset`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Asset "discord.Asset") for the avatar the user has.
If the user does not have a traditional avatar, `None` is returned. If you want the avatar that a user has displayed, consider [`display_avatar`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User.display_avatar "discord.User.display_avatar").
!d discord.Embed.set_image for setting the pfp as image
set_image(*, url)```
Sets the image for the embed content.
This function returns the class instance to allow for fluent-style chaining.
How do i make my bot status like watching (members) in (guilds)
or something like that
!d discord.Client.change_presence
await change_presence(*, activity=None, status=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Changes the client’s presence.
Example
```py
game = discord.Game("with the API")
await client.change_presence(status=discord.Status.idle, activity=game)
``` Changed in version 2.0: Removed the `afk` keyword-only parameter...
so i made an echo command:
@bot.command(name='echo')
async def name(ctx, *, repeat: str):
if ctx.author.id == 654818715183087626:
await ctx.send(f"{repeat}")
await ctx.message.delete()
return
else:
await ctx.message.delete()
return
but i want it to be able to sent in other channels, how would i do that? (i.e !echo #b 'Hello' (sent in #a))
async def foo ( ctx, c: discord.TextChannel,*, stuff):
await c.send(stuff)
?
hold on
@bot.command(name='echo')
async def name(ctx, c: discord.TextChannel, *, repeat: str):
if ctx.author.id == 654818715183087626:
await ctx.send(repeat)
await ctx.message.delete()
return
else:
await ctx.message.delete()
return
? @slate swan
ctx.send sends to invocation channel... you need to use c.send
c.send(repeat)?
yeah
oooh tyy
question if i wanted to make it cross-serveral, would i make it discord.TextChannel.id?
@slate swan
no it will still work
how so ?
discord.py does that internally
yes
but what if theres multiple channels called the same thing, i.e general?
use the id or mrnyit
would it not be better to just use discord.TextChannel.id?
oh
how would i do it
wait
does discord.TextChannel count for both ID and name?
mention too yes
i did !echo 979044034070843393 beep boop, does this work? and it didnt work
do i need to do @<channelid>?
.
can u help me in #help-cheese 🥹
explicit search result
rust is better than cpp
java is better than rust
php is better than java
java isnt even low level 
java is better than evferything
java is better than rust because it have a huge developer ecosystem and community, along with more frameworks to choose from. Rust have been declining popularity right now so its not the best choice.
sounds just like py vs js case
and something being used in mass doesn't make it better
anyways, offtopic
Ah yes declining popularity
Zeffo took that personally
😔 rust is an emotion and im rusted
Get some WD-40 and you'll be fine
the pyo3 keeps declining it

iron oxide be like:
every channel im in is just dead
🥹
rip
u know django?
thats what i did and look and it 💀
have patience
Um, hey.
So i have a command which loops through every member in a guild, and if they don't have role xyz, it would assign them those roles.
So my question is, how would i get those peoples' names who Doesn't have the role?
I tried
return member.name``` but it just sends someone who already has it.
.
```py
x = ctx.guild.get_role(...)
y = ctx.guild.get_role(...)
z = ctx.guild.get_role(...)
for member in ctx.guild.members:
if [x, y, z] not in member.roles:
return "uhh"```
I'm using discord.py 2.0
idk django but can help with fastapi
U guys got any good resources for learning how to implement databases to bots?
I just wanna check one out. And if I feel like I still lack understanding, would need to go back to some basic stuff lol
@client.command(pass_context=True)
async def cemo(ctx):
with open("my_image.png", "r") as file:
file = file.read()
await create_custom_emoji(name="my_image",image=file)
It doesn't work like that
!e
member_roles = ["role1", "role2", "role3"]
target_roles = ["role1", "role2"]
print(target_roles in member_roles)
@naive briar :white_check_mark: Your 3.11 eval job has completed with return code 0.
False
Is it in the same directory as the python file that code is in?
oh yea i forgot about that
🤨
Code
async def on_submit(self, interaction: discord.Interaction):
view = appresponse()
await interaction.response.send_message(
f'Your application was submitted successfully, {interaction.user.mention}!', ephemeral=True)
embedVar = discord.Embed(title=f"{interaction.user}'s Application",
description=f"User", color=0x351156)
await channel.send(embed=embedVar, view=view)
await view.wait()
if view.value is None:
return
else:
await embedVar.reply(f"{view.value} is accepted.")```
error
```py
Traceback (most recent call last):
File "D:\pythonProject\venv\lib\site-packages\discord\ui\modal.py", line 186, in _scheduled_task
await self.on_submit(interaction)
File "D:\pythonProject\main.py", line 91, in on_submit
await embedVar.reply(f"{view.value} ")
AttributeError: 'Embed' object has no attribute 'reply'
you need to do interaction.original_message() or smth and then reply to that or just interaction.followup.reply or smth
alr
await interaction.followup.reply(f"{view.value} is accepted.")
``` this ?
You can try that
how do i make a command that creates a role
Task exception was never retrieved
future: <Task finished name='discord-ui-modal-dispatch-569e8ea75a4b3dc48c4b6f199cd7b0d8' coro=<Modal._scheduled_task() done, defined at D:\pythonProject\venv\lib\site-packages\discord\ui\modal.py:177> exception=InteractionResponded('This interaction has already been responded to before')>
Traceback (most recent call last):
File "D:\pythonProject\venv\lib\site-packages\discord\ui\modal.py", line 186, in _scheduled_task
await self.on_submit(interaction)
File "D:\pythonProject\main.py", line 91, in on_submit
await interaction.followup.reply(f"{view.value} is accepted.")
AttributeError: 'Webhook' object has no attribute 'reply'
During handling of the above exception, another exception occurred:
There's no reply method in Webhook object
Thought so
You need to fetch the original message and then reply to that or use the undocumented methods to prevent an API call and reply to message
whats the command for that
!d discord.Guild.create_role
await create_role(*, name=..., permissions=..., color=..., colour=..., hoist=..., display_icon=..., mentionable=..., reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Creates a [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role") for the guild.
All fields are optional.
You must have [`manage_roles`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") to do this.
Changed in version 1.6: Can now pass `int` to `colour` keyword-only parameter.
New in version 2.0: The `display_icon` keyword-only parameter was added...
TYSM
It looks like he's sending the message with a channel object
Huh?
🤷
ah that
then he can just assign it to a variable and then use reply
the error tells you exactly what your issue is
how can I make my bot.user.display_avatar.url into a "bytes-like-object" so i can use it as my avatar in a webhook?
await read()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Retrieves the content of this asset as a [`bytes`](https://docs.python.org/3/library/stdtypes.html#bytes "(in Python v3.11)") object.
Or maybe you don't have to put it in BytesIO if I misunderstood something
Traceback (most recent call last):
File "/home/container/.local/lib/python3.9/site-packages/jishaku/features/python.py", line 145, in jsk_python
async for send, result in AsyncSender(executor):
File "/home/container/.local/lib/python3.9/site-packages/jishaku/functools.py", line 109, in _internal
value = await base.asend(self.send_value)
File "/home/container/.local/lib/python3.9/site-packages/jishaku/repl/compilation.py", line 140, in traverse
async for send, result in AsyncSender(func(*self.args)):
File "/home/container/.local/lib/python3.9/site-packages/jishaku/functools.py", line 109, in _internal
value = await base.asend(self.send_value)
File "<repl>", line 4, in _repl_coroutine
bytes = _bot.user.display_avatar.url.read()
AttributeError: 'str' object has no attribute 'read'
No, just user.display_avatar.read not user.display_avatar.url.read
I see
Traceback (most recent call last):
File "/home/container/.local/lib/python3.9/site-packages/jishaku/features/python.py", line 145, in jsk_python
async for send, result in AsyncSender(executor):
File "/home/container/.local/lib/python3.9/site-packages/jishaku/functools.py", line 109, in _internal
value = await base.asend(self.send_value)
File "/home/container/.local/lib/python3.9/site-packages/jishaku/repl/compilation.py", line 140, in traverse
async for send, result in AsyncSender(func(*self.args)):
File "/home/container/.local/lib/python3.9/site-packages/jishaku/functools.py", line 109, in _internal
value = await base.asend(self.send_value)
File "<repl>", line 6, in _repl_coroutine
web = await _ctx.channel.create_webhook(name = "Aziel", avatar = bot_av, reason = "This was a test!")
File "/home/container/.local/lib/python3.9/site-packages/discord/channel.py", line 516, in create_webhook
avatar = utils._bytes_to_base64_data(avatar) # type: ignore
File "/home/container/.local/lib/python3.9/site-packages/discord/utils.py", line 591, in _bytes_to_base64_data
mime = _get_mime_type_for_image(data)
File "/home/container/.local/lib/python3.9/site-packages/discord/utils.py", line 577, in _get_mime_type_for_image
if data.startswith(b"\x89\x50\x4E\x47\x0D\x0A\x1A\x0A"):
AttributeError: '_io.BytesIO' object has no attribute 'startswith'
My code:
import io
bytes = await bot.user.display_avatar.read()
bot_av = io.BytesIO(bytes)
web = await ctx.channel.create_webhook(name = "Aziel", avatar = bot_av, reason = "This was a test!")
await web.send(f"Hey! This was {ctx.author} testing a webhook!")
Yeah, just pass the bytes in. No need to put it in io.BytesIO
Uh
If you mean the links, it's as follows.
[Click to ...](https://....)```
Hello guys, could somebody help me make a discord bot? Im doing it with python coding language and im making it on replit. But the problem is whenever i run the code the bot doesnt start up
Server rules is the title
Follow discords... Is probably the field name
The links are value
And the are just values with lots of \n
but my guess is that the reason the bot doesnt work is cuz of its token, and also here are the errors i get when i try to run the code
Error (If there is no token put in code): https://paste.pythondiscord.com/owugerabus
Error (With token): https://paste.pythondiscord.com/cavufijutu
Rate limited
- You have 2 bot constructors.
- It's discord.Intents.deafult()
- You have indention error in your on_ready event.
Reset ur token
what are bot decorators?
... = commands.Bot()
This is called bot deocrators constructors
Cloudflare rate limited replit 🤷
is it cuz i im using uptime robot so my bot is up 24/7?
so what should i do to fix that
I might have mixed up deocrators and constructors
You shouldn't be using replit if you need your bot to be running 24/7
like this?
idk what else to use for hosting my discord bot
from discord import Intents
intents = discord.Intents.default
like this?
No, define them on the 2nd last line
intents = Intents.default
Change it to
intents = discord.Intents.default()
You can look at #965291480992321536
okay, i did that
Cool
I removed the 2nd one, and after that the code under client.event got underlined in red
3rd one
removed that, still getting an error
And what's the error?
On the right side of the console
There should be another option
Type kill 1 in there
Ok yeah, now run it
🤷♀️
* Environment: production
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead.
* Debug mode: off
* Running on all addresses.
WARNING: This is a development server. Do not use it in a production deployment.
* Running on <censored ip> (Press CTRL+C to quit)
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/http.py", line 300, in static_login
data = await self.request(Route('GET', '/users/@me'))
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/http.py", line 254, in request
raise HTTPException(r, data)
discord.errors.HTTPException: 401 Unauthorized (error code: 0): 401: Unauthorized
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "main.py", line 49, in <module>
client.run("<token here>")
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 723, in run
return future.result()
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 702, in runner
await self.start(*args, **kwargs)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 665, in start
await self.login(*args, bot=bot)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 511, in login
await self.http.static_login(token.strip(), bot=bot)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/http.py", line 304, in static_login
raise LoginFailure('Improper token has been passed.') from exc
discord.errors.LoginFailure: Improper token has been passed.
172.31.128.1 - - [19/Nov/2022 17:08:06] "GET / HTTP/1.1" 200 -```
ok well i put the token in, and the bot starts but it doesnt print "Bot Online" which its supposed to do
also 1 more thing, how would i make the bot have an embed come with a link?
!d discord.Embed
class discord.Embed(*, colour=None, color=None, title=None, type='rich', url=None, description=None, timestamp=None)```
Represents a Discord embed.
len(x) Returns the total size of the embed. Useful for checking if it’s within the 6000 character limit.
bool(b) Returns whether the embed has any data set.
New in version 2.0.
x == y Checks if two embeds are equal.
New in version 2.0...
Doesn't look like it to me
just use https:// before a link and it will automatically embed the link
for example, when i send the link theres a embed but my bot doesnt embed when i send link
It is:
disclaimer: this works on dark theme only and is not truly transparent
There are 2 types of "transparent" embeds:
- one that uses the embed background color
- one that uses the discord background color
Embed BG = 0x2F3136 # Gives rounded corners
Discord BG = 0x36393E # Gives pointy corners
https://media.discordapp.net/attachments/381963689470984203/728409586448597072/unknown.png

Well, isn't hyperlinks only usable in Embeds and normal message by webhooks? Or am i missing something
from discord.py server
Interesting, didn't know that before
normal message by webhooks
webhooks ae not only some normal messages. they also consist of the channels followed and interactions
What the heck? 
Got invoked with: <prefix> pat @ user
async def pat(
self,
ctx: MessageContext,
user: Union[discord.Member, discord.User],
*,
_: Optional[str] = None
) -> None:
What's weird about it
Did you even read the error?
do you know what Union means in math?
Yes, and that has nothing to do with it.
I could also use Member | User and it also screams at me
you don't need to use both
That isn't why it errors
type hint it discord.Member
isn't that a bad arg
What i meant was, you can use hyperlinks on text message which are sent by webhook 🤷♀️
.User and .Member is diff
That doesn't even matter
I am not accessing any values which aren't present in both.
dont think union is supported in slash commands yet
also .User is when a person a dming the bot or in dms
so no reason u need .User
how do you load cogs now in version 2.0?
Same as before but with await
it now retuns None
and gives the Nonetype error
i havent changed anything other than adding the await thing
does this example help you?
# Load cogs
initial_extension = []
for filename in os.listdir("./cogs"):
if filename.endswith(".py"):
initial_extension.append("cogs." + filename[:-3])
if __name__ == '__main__':
for extension in initial_extension:
client.load_extension(extension)```
where are the examples of the buttons
thanks
everytime i close and run the bot the ranks goes to 0 again
i use db how do i save it
where's your code which should persist your data?
root@localhost:~# python3 run.py
Traceback (most recent call last):
File "/root/project/script/main.py", line 3, in <module>
from imports import *
File "/root/project/script/imports.py", line 19, in <module>
from discord_slash import SlashCommand, SlashContext
ModuleNotFoundError: No module named 'discord_slash'
did you write the run.py file yourself?
I feel like you've just downloaded some project of a YT video & you're now trying to run it
no its a bot i bought pip3 install discord-py-slash-command==3.0.3 but i gotijt
aight, gl
The repo is back?
should it be gone?
It was yesterday

yup, rip that maintainability
This is why I don't like the the discord bot "market"
No idea where people even buy bots etc, I guess that's a good thing
@hollow gazelle unfortunately I think you've wasted your money here - discord-py-slash-command isn't very good and is no longer on PyPi
its bc im using a putty
but it workedonce i did it
it won't for long
Yeah the library is discontinued i believe
discord.py supports slash commands, so we don't need 3rd party libraries like these anymore
Wait it's unbanned?
What's the problem?
Guys, this is my first time writing a bot. I have this problem, I seem to have started the bot, it's logged into the network on the discord server, but for some reason when I run the code it doesn't work.
What's error
It says connected lol
The bot is connected, I added code to make it respond to the word "ping" with "pong". But it doesn't answer anything.
Show ping pong code that's the problem
take a look at the console, it may tell you where the error is
Thank you, the code is working. Although I wrote !ping
Why bot=False lol
Self Bot
What was problem
!rule 5
5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.
I don't know, a friend did something in the terminal and the problem solved itself.
!rule 2
2. Follow the Discord Community Guidelines and Terms Of Service.
Self bots are against tos @slate swan
:
np 
This happens when im trying to run the bot API web.
I suppose some model issues.. OAuth2 tokens are not being saved to db
class User(DiscordEntity):
"""Base User model, meant to be reference by extensions"""
async def fetch(self, bot: InteractionBot) -> DUser | None:
"""Returns the associated user id for the given user Model."""
return bot.get_user(self.id)
class Welcomer(Guild, Model):
guild = OneToOneField("Bot.Guild")
channel_id = BigIntField(null=False)
enabled = BooleanField(default=False)
title = TextField(null=True)
description = TextField(null=True)
icon = TextField(null=True)
image = TextField(null=True)
color = TextField(null=True)
footer_text = TextField(null=True)
footer_icon = TextField(null=True)
class OAuth2User(Model):
"""Oauth2 User."""
id: str
token: str
expires_in: int
the discord_slash import refers to a no longer existing library but discord-py-slash-command is still there, its just changed to a somewhat outdated mirror of discord-py-interactions
oauth_response = await OAuth2User.get(id=member.id)
print(oauth_response.token)
add_to_guild(oauth_response.token, member.guild.id, member.id)
I also tried printing the oauth token to see if there's something
anyone knows anything about OAuth2 tokens?
This is a database related issue, ask in #databases
People don't really reply there... Do you have some knowledge for this?
import discord
from discord.ext import commands
intents = discord.Intents.default()
intents.presences = True
intents.members = True
intents.message_content = True
bot = commands.Bot(command_prefix='!', intents=intents)
@bot.command()
async def ping(ctx):
await ctx.send('pong')
Question why the bot answers four times "pong"
maybe you are running it 4 times
I started to change the answer and restart the bot and now it answers all the answers it had before.
can someone give me an example of a permissions overwrite ?
!d discord.PermissionOverwrite the docs should have it
overwrite = discord.PermissionOverwrite()
overwrite.send_messages = False
overwrite.read_messages = True
await channel.set_permissions(member, overwrite=overwrite)
Is it possible to create an separate cog_check without monkey patching discord.py?
maybe try invoking the predicates of each check you want to run, e.g. py checks = [commands.guild_only(), commands.has_permissions(manage_guild=True)] return await discord.utils.async_all(c.predicate(ctx) for c in checks)
lgtm
https://stackoverflow.com/questions/59126137/how-to-change-activity-of-a-discord-py-bot is this valid? can anyone explain
its been 8 hours and nobody is giving my question a sh!t :D
how do I store the my bot object in the setup method of an extension in a variable named "Aziel"?
what's your question
Could you explain better?
no worry i deleted the whole file and is currently following a whole new tutorial
I want to get my bot object so I can use it in my file, I was told I can get my object using the setup extension method but I’m unsure how
Hello! How do I scrape the contents of a discord embed in a channel?
Are you talking about Cogs?
nope
extensions
random .py file which I want access to my bot object in (ping when reply pls)
define it in your constructor
!xy
xy-problem
The XY problem can be summarised as asking about your attempted solution, rather than your actual problem.
Often programmers will get distracted with a potential solution they've come up with, and will try asking for help getting it to work. However, it's possible this solution either wouldn't work as they expect, or there's a much better solution instead.
For more information and examples, see http://xyproblem.info/
Is it possible to add buttons to existing messages?
Yes
message.edit has a view kwarg
alright thanks
eh?
how do i display a user’s pfp in an embedded message with a python code
whats the best way to reference someones display name?
!d discord.Member.display_name
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.
!d discord.Embed.set_image
set_image(*, url)```
Sets the image for the embed content.
This function returns the class instance to allow for fluent-style chaining.
!d discord.Member.avatar
property avatar```
Equivalent to [`User.avatar`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User.avatar "discord.User.avatar")
!d discord.Asset.url
property url```
Returns the underlying URL of the asset.
thanks!
do i just write set_image(*, url)
Does anyone know how to use BaseActivity in discord.py 2.0
I think i saw your channel earlier
I think that's a parent class to some of the built in activity types that you can choose from. Not sure you're supposed to be using that directly
What type of status do u wanna show?
its alright ive got it to work now
Cool
When I use this it's being stored as a property object, is there any way for it to read the way it reads inside disc?
like with getitem (square brackets)?
member["display_name"]?
im not sure. id like to see "Danco#1903" in my database, but right now im seeing <property object at [memory location]>
Are you literally using discord.Member.display_name
oh
yeah
you need to have an actual instance of that object
how you actually get an instance depends on what you're trying to do
if it's a command it should be availbe via context
this is what i have right now, line 18
if an event, it should be a param of the event object
what member do you want to insert
Why are you storing their name anyway?
that's the question
the target of the command
is this a command func?
What is target
You'd wanna store their id probably, depending on what this is for
yeah, im storing their name for tracking a currency, will make easier to read displays
use id!!
Use id, get their name when you actually need to display it
There's no reason to store this
so when i store the currency that they have, thatll be connected to their disc id. and then when i use a command to show how much currency people have i can pull the display name at that point?
how to ignore every error in discord.py?
whats the url
try, except
But it's better to fix then 🙄
why would you want this???
wtf ur question
Huh
wtf ur question
i guess they like having broken code 
Just downloaded a random code from GitHub
You have fix your issue?
yeah, real helpful group here
Everything you wanna store from discord (in database or whatever),use the id
That's why ids existing 😆
you know, now that i think of it that totally makes sense lol
i have a habit of overcomplicating things so this all tracks
go to the dev portal. open ur app and go to the oath2 section. then go to general and select the stuff for the default invite
it work, thanks
can i have 2 database on the same on_ready?
what do you mean by that?
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
did that and look
Why do I keep getting this error?
you got ratelimited
run kill 1 in the shell and it'll reset your IP
Another option is don't use a free host (replit/heroku)... you'll get this error a lot. get a $1/month vps with your own IP so it won't happen
?
I’ve already have a thorough look through that
doesn’t tell me how to get my bot object
I forgot, what was the method to run synchronous code asynchronously with discord bots / asyncio?
Why would you set a default value for it
if I just pass in bot, does that mean I can use reference bot anywhere else in my code and it’ll give me my bot object?
The load_extension will do all the work
can someone tell me why is this happen, i just trying to make discord bot with discordpy, but this happen when i run it...
Replit got rate limited
what should i do
async def setup(bot):
Aziel = await bot.load_extension('logger')
like so?
thanks
bot.load_extension should be in your main.py and the setup function should call your class passing bot as parameter, the class should accept in it's init an argument (bot)
this should work
I’m not using any classes?
import discord
#my custom func
async def log(…):
…
@glad cradle this is somewhat what my file looks like and in my custom func, I want my bot object
how do i display a users pfp in an embedded message
.set_author()
.set_image()
.set_thumbnail()
.set_footer()
pick which one applies to you
how do i get their pfp
member objects have a .avatar attribute
Well, idk You could use a shitty global variable but I don't think that's a good thing, why don't you use a class?
!d discord.User.avatar
property avatar```
Returns an [`Asset`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Asset "discord.Asset") for the avatar the user has.
If the user does not have a traditional avatar, `None` is returned. If you want the avatar that a user has displayed, consider [`display_avatar`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User.display_avatar "discord.User.display_avatar").
idk what to sublass
you don't have to subclass anything
You need to subclass commands.Cog only for cogs but yours is an extension, not a cog
do i just write property avatar
import discord
class CustomFunctions:
def __init__(self, bot: commands.AutoShardedBot)
self.bot = bot
async def log(ctx):
await ctx.send(self.bot.user.display_avatar.url)
async def setup(bot):
pass
like this?
there is avatar.url for getting the url
I've never done it so I don't know if it works, you can try, The point is that discord.py won't automatically invoke your feature because it's not a command, you'll have to find some way
import discord
class CustomFunctions:
def __init__(bot)
self.bot = bot
async def log(ctx):
await ctx.send(self.bot.user.display_avatar.url)
async def setup(bot):
CustomFunctions(bot)
I’ll be calling my function since I’m gonna import it
from logger (my file name) import log
then await log()
should do the trick
if you'll import it then you don't need to call the class in the setup
in your logger you have a bot object right?
^ template of what my code currently looks like
my issue is idk how to get my bot object
inside this file
I do not understand why you need a Bot object in your logger file, in the logger file you usually set and create a custom logger, you don't send log messages or other things
…
you’re getting confused with my function name
I’m not actually making a logger
I was giving you an example
for the sake of confusion
ah
need help ith blacklist command
This can work for you if and only if you can use the newly object created in the setup function.
otherwise the class will have no Bot object
?
import discord
class CustomFunctions:
def __init__(self, bot: commands.AutoShardedBot)
self.bot = bot
async def log(ctx):
await ctx.send(self.bot.user.display_avatar.url)
async def setup(bot):
await bot.load_extension('logger')
like that?
CustomFunctions(...) is creating a CustomFunctions object, you can use and access the Bot object only after the initialization of the class (so when you're creating a class object and passing a bot object), if you find a way to import the object out of the file then you can use the class with the Bot object
bot.load_extension should go in your main.py (where you have defined a bot object)
"if you find a way to import the object out of the file then you can use the class with the Bot object"
what?
sure
utils/logger.py
import discord
from discord import Webhook
class CustomChecks:
def __init__(self, bot: commands.AutoShardedBot):
super().__init__()
async def log():
aziel_avatar = bot.user.display_avatar.url
e = discord.Embed(colour = 0x2f3136)
e.title = "Testing my custom function!"
e.set_image(url = aziel_avatar)
async def setup(bot):
CustomChecks(bot)
await bot.load_extension('utils.logger')
cogs/info.py
import discord
from utils.logger import log
class Info(commands.Cog):
def __init__(self, bot: commands.AutoShardedBot):
self.bot = bot
@commands.command()
async def ping(self, ctx):
await log()
async def setup(bot):
await bot.add_cog(Info(bot))
@glad cradle like this?
how to run blocking code for discord bot? I forgot
just run it
I remember it blocking other commands, is this no longer the case?
it is most definitely still the case
blocking code in an async context blocks the event loop
I remember there was a way to run blocking code
are you talking about asyncio.run_in_executor?
_ _
Most likely
it throws RuntimeError: main thread is not in main loop 🤔
oh shit I fixed it
👍
my blocking code was plotting with matplotlib, I added matplotlib.use("Agg") and now it works :)
bro you can do
utils/logger.py
...
class CustomChecks:
def __init__(self, bot):
self.bot = bot
async def log(self):
# access the bot with self.bot
...
cogs/info.py
from utils.logger import CustomChecks
...
@commands.command()
async def ping(self, ctx):
logger_class = CustomChecks(self.bot)
await logger_class.log()
...
...
you don't need to load as extension "utils.logger", you can just import it where you need it
... are elipsis that you can substitute with your previous code
I thought you didn't have access to the Bot object where you had to use the class
forgot to say this worked btw ^^ tysm!
how can i execute command after music ended?
voice.play(discord.FFmpegPCMAudio(executable = "C:/ffmpeg/bin/ffmpeg.exe", source = URL, ** FFMPEG_OPTIONS), after= print("Test"))```
using the after parameter as you're doing
!d discord.VoiceClient.play
play(source, *, after=None)```
Plays an [`AudioSource`](https://discordpy.readthedocs.io/en/latest/api.html#discord.AudioSource "discord.AudioSource").
The finalizer, `after` is called after the source has been exhausted or an error occurred.
If an error happens while the audio player is running, the exception is caught and the audio player is then stopped. If no after callback is passed, any caught exception will be logged using the library logger.
Changed in version 2.0: Instead of writing to `sys.stderr`, the library’s logger is used.
The finalizer, after is called after the source has been exhausted or an error occurred.
ah.. but it called right after play executed
!passte
yes because you didn't pass a callable
!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.
you passed None
either pass a function ```py
def print_something(exception):
print("whatever")
.play(..., after=print_something)
.play(..., after=lambda e: print("whatever"))
Does it work with functools.partial?
yes
Sry but what is lambda?
so i use database for my bot for level system but everytime i rerun the bot the levels goes to 0
how can i make it stay like it was
Which database?
aiosqlite
Are you remembering to commit after executing a query?
ill check
cant here
now it is saving it but sending twice
Because you're returning on the line above
yeah fixed
but that
Code?
What is sleep a bot
!d discord.Client - set the status kwarg
class discord.Client(*, intents, **options)```
Represents a client connection that connects to Discord. This class is used to interact with the Discord WebSocket and API.
async with x Asynchronously initialises the client and automatically cleans up.
New in version 2.0.
A number of options can be passed to the [`Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client").
catgal maybe do u know?
.
!d discord.Status.idle - to this
The member is idle.
What's the problem
its sending everything twice
voice.play(discord.FFmpegPCMAudio(executable = "C:/ffmpeg/bin/ffmpeg.exe", source = URL, ** FFMPEG_OPTIONS), after=lambda e: music(ctx))```
RuntimeWarning: coroutine 'music' was never awaited
???
await it
You may have 2 instances of the bot running or having multiple process_commands
ill check
SyntaxError: 'await' outside async function
you should asyncio.create_task or asyncio.run_coroutine_threadsafe
you're welcome
hi guys , how can i set an overwrite for 'everyone' as 'connect' = false
overwrites = {
ctx.guild.default_role: discord.PermissionOverwrite(connect = False)
}
what do u mean
How to import the slash commands? I used the from discord import app_commands and I got this error: ImportError: cannot import name 'app_commands' from 'discord'
What's the library?
discord library, no?
I found someone's tutorial on yt how to do it and it doesnt work for me
or how to import the slash commands
what can i do instead of
int(datetime.datetime.now().timestamp())
bc it says
Command raised an exception: AttributeError: type object 'datetime.datetime' has no attribute 'datetime'
You imported datetime.datetime not datetime
import datetime
from datetime import datetime, timedelta
oh
do i remove one datetime
Remove the first one
okay ty!
@tasks.loop(seconds=30)
async def twitter_stream(self):
print("Loop started")
bearer_token = self.config['twitter_token']
auth = {
"Authorization": f"Bearer {bearer_token}",
"User-Agent": "v2FilteredStreamPython"
}
url = 'https://api.twitter.com/2/tweets/search/stream'
session_timeout = aiohttp.ClientTimeout(total=5)
async with aiohttp.ClientSession(raise_for_status=True, headers=auth, timeout=session_timeout) as session:
async with session.get(url) as r:
async for line in r.content:
c = line.decode("utf-8")
c = c[:-2]
if c:
#Do a thing here coz we can.
print("Loop ended")
``` Why does doing this cause the entire thing to loop back to the start of the function instead of first concluding?
I don't understand what you're saying
So when I run the code.
the first print statement runs. then it hits the clientsession part, where it keeps the connection open.
then once the timer hits (in this case 5 seconds), it returns back to the first print statement instead of going to the next part which is the last print statement
session_timeout = aiohttp.ClientTimeout(total=5) is basically saying how long the entire session remains open for.
discord/ext/tasks/__init__.py lines 155 to 160
self._valid_exception = (
OSError,
discord.GatewayNotFound,
discord.ConnectionClosed,
aiohttp.ClientError,
asyncio.TimeoutError,```
it catches those exceptions for reconnection
I'm not sure if aiohttp raises a TimeoutError but if it does, that might answer your question
I was about to explore that. Had to go afk for a moment. When I ran the code without the loop i get the timeout error
!e
int("owo")
@naive briar :x: Your 3.11 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | ValueError: invalid literal for int() with base 10: 'owo'
do i remove the int or?
How can i get those members' name?
try and ask a better question 😉
Get it from audit logs
@bot.command()
@commands.has_permissions(manage_messages=True)
async def warns(ctx, member: nextcord.Member):
async with bot.db.cursor() as cursor:
await cursor.execute("SELECT reason, time FROM warns WHERE user = ? AND guild = ?", (member.id, ctx.guild.id,))
data = await cursor.fetchone()
if data:
em = nextcord.Embed(title=f"{member.name}#{member.discriminator}'s Warnings", color=0x99a2d1)
warnnum = 0
for table in data:
warnnum += 1
em.add_field(name=f"Warning {warnnum}", value=f"Reason: {table[0]} | Date: <t:{int(table[1])}:F>")
await ctx.send(embed=em)
else:
em2 = nextcord.Embed(title="Warning Error", description="No warnings found!", color=nextcord.Color.red())
await ctx.send(embed=em2)
await bot.db.commit()```
```nextcord.ext.commands.errors.CommandInvokeError: Command raised an exception: ValueError: invalid literal for int() with base 10: 'o'
hello guys i need help with a prefix bot in discord. its supposed to say of i type ?id to reply, but i couldn't find anything that could help. someone help me?
What have you got so far?
What do you need help with?
maybe start by learning the basics of python and work your way up
Okay but here we help with errors and tips & tricks.
i know but this is myy last hope
state the exact line
Well have you installed Python?
yes
lol
learning Python while coding a bot is a steep learning curve
ik but its for my server
em.add_field(name=f"Warning {warnnum}", value=f"Reason: {table[0]} | Date: <t:{int(table[1])}:F>")
ye thats why is said to learn the basics first
print table[1]for me
also its type pls
It's fun tough.
What kind of research have you done? What are you using? Discord.py?
yea kinda discord.py
i will okay
have you even thought of where to host this bot of yours?
yes, neither replit or python
?
host like running?
mhm
if i got the code i would run it on python windows or replit
python windows? so you'll be selfhosting?
What do you guys think about guilded?
at first to test yes
that's... obvious
to make sure bot doesn't have problems
what is obvious
that you'd selfhost when testing...
i don't understand sorry
no worries
Traceback (most recent call last):
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\ext\commands\core.py", line 165, in wrapped
ret = await coro(*args, **kwargs)
File "c:\Users\PC\Desktop\Aleccy Bot\main.py", line 96, in warns
em.add_field(name=f"Warning {warnnum}", value=f"Reason: {table[0]} | Date: <t:{int(table[1])}:F>")
ValueError: invalid literal for int() with base 10: 'o'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\client.py", line 502, in _run_event
await coro(*args, **kwargs)
File "c:\Users\PC\Desktop\Aleccy Bot\main.py", line 605, in on_command_error
raise error
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\ext\commands\bot.py", line 1382, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\ext\commands\core.py", line 948, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\ext\commands\core.py", line 174, in wrapped
raise CommandInvokeError(exc) from exc
nextcord.ext.commands.errors.CommandInvokeError: Command raised an exception: ValueError: invalid literal for int() with base 10: 'o'```
you still didn't do what I asked you to...
yeah, ABOVE the add field 🧠
with some newlines in between or whatever, I also needed the type
oof
it printed o
type?
what did you print?
it should be str
I need confirmation
you can never be too sure with these kind of screenshots
print(table[1])
print(f"table: {table}\n{table[1]}, type: {type(table[1])}")
table: No reason provided
o, type: <class 'str'>
do i change the int to str
well, do you expect that to turn into zero?
if they have 0 warnings yes
await cursor.execute("CREATE TABLE IF NOT EXISTS warns (user INTEGER, reason TEXT, time INTEGER, guild INTEGER)")
what db is this? aiosqlite?
yes
this is just rubbish
yeah
yup, that's great
so this means the time isn't fetched correctly, right?
since there's not a single column where the time is empty, right?
i think yes
can you also see the warning nr?
so you can actually show me what row you're fetching
like the create table?
no
I might also suggest to you to use
self._conn = await aiosqlite.connect(DATABASE_PATH)
self._conn.row_factory = aiosqlite.Row # <--- look at this line```
a rowfactory
data = await cursor.fetchone()
if data:
em = nextcord.Embed(title=f"{member.name}#{member.discriminator}'s Warnings", color=0x99a2d1)
warnnum = 0
for table in data:
warnnum += 1
print(f"table: {table}\n{table[1]}, type: {type(table[1])}")
em.add_field(name=f"Warning {warnnum}", value=f"Reason: {table[0]} | Date: <t:{int(table[1])}:F>")
that way, you can access columns in a db like you would with a dict
example
table['time'] instead of table[0]
so the self._conn is probably something else in your case
probably self.db or whatever
why?