#discord-bots
1 messages ยท Page 159 of 1
what event
named on_presence_update
it used to log tho
u missing ur intents then
!d discord.on_presence_update
discord.on_presence_update(before, after)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member") updates their presence.
This is called when one or more of the following things change:
โข status
โข activity
This requires [`Intents.presences`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.presences "discord.Intents.presences") and [`Intents.members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.members "discord.Intents.members") to be enabled...
nice
spooky.exe smart
I think that was genuine ๐ณ
@client.event
async def on_presence_update(before, after):
print("H")
if str(before.raw_status) == "offline":
return
else:
for g in db[f"stsgr"]:
guild = client.get_guild(g)
mem= guild.get_member(after.id)
print(mem.name,"#2")
vanity = db[f"{g}stsrolek"]
roleid = db[f"{g}stsroler"]
role=guild.get_role(roleid)
print(role.name)
try:
bst = mem.activities[0].name
ast = before.activities[0].name
if vanity in bst:
if not vanity in ast:
await mem.add_roles(role, reason="Added Vanity In Status")
print(after.name,"#3")
elif vanity in ast:
if not vanity in bst:
if role in mem.roles:
await after.remove_roles(role, reason="Removed Vanity From Status")
print(after.name,"#4")
except:
pass
btw it isnot giving the role
the fuctions print(role.name) is not wokring
though it is in the database
Traceback (most recent call last):
File "/home/runner/Enc/venv/lib/python3.8/site-packages/discord/client.py", line 409, in _run_event
await coro(*args, **kwargs)
File "main.py", line 129, in on_presence_update
await mem.add_roles(role, reason="Added Vanity In Status")
File "/home/runner/Enc/venv/lib/python3.8/site-packages/discord/member.py", line 1014, in add_roles
await req(guild_id, user_id, role.id, reason=reason)
File "/home/runner/Enc/venv/lib/python3.8/site-packages/discord/http.py", line 738, in request
raise Forbidden(response, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50001): Missing Access```
why am i getting this
!d discord.Intents.presences
Whether guild presence related events are enabled.
This corresponds to the following events:
This also corresponds to the following attributes and classes in terms of cache...
Sorry, you can't do that here!
Make sure you have enable the right intents!
no that is fixed btw what is missing access
Bot have no permission to do that (you are probably trying to edit a role higher than bot.)
maybe his bot missing permissions hm
Show code
@client.event
async def on_presence_update(before, after):
print("H")
if str(before.raw_status) == "offline":
return
else:
for g in db[f"stsgr"]:
guild = client.get_guild(g)
try:
mem= guild.get_member(after.id)
print(mem.name,"#2")
except:
return
vanity = db[f"{g}stsrolek"]
roleid = db[f"{g}stsroler"]
role=guild.get_role(roleid)
print(role.name)
bst = mem.activities[0].name
ast = before.activities[0].name
if vanity in bst:
if not vanity in ast:
print(after.name,"#3")
print(guild.name)
await mem.add_roles(role, reason="Added Vanity In Status")
print(after.name,"#4")
elif vanity in ast:
if not vanity in bst:
if role in mem.roles:
print(after.name,"#3")
await after.remove_roles(role, reason="Removed Vanity From Status")
print(after.name,"#4")
```
if vanity in bst:
if not vanity in ast:
print(after.name,"#3")
print(guild.name)```
upto this it is working
even it is loggin #4
You are getting the error when the bot trying to add the role (mem.add_roles())
btw now no error it is even printing #4 after add role btw not adding role
Btw
ok now it is working
can i popup modals through ctx?
Yep
!d discord.Client.add_view
add_view(view, *, message_id=None)```
Registers a [`View`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.View "discord.ui.View") for persistent listening.
This method should be used for when a view is comprised of components that last longer than the lifecycle of the program.
New in version 2.0.
takes the buttons class ass parameter
add this on either on_ready or setup_hook [recommended]
Maybe let your cat to fix that
Buy dog and thanks me later
cats are cutie :3
Hello I have a question. Is there something wrong with this code bcs my bot is not responding on the command coinflip.
import discord
import random
import asyncio
#Perms
intents = discord.Intents.default()
intents.message_content = True
intents.presences = True
intents.dm_typing = True
intents.bans = True
intents.dm_messages = True
intents.dm_typing = True
intents.guild_messages = True
intents.members = True
intents.typing = True
intents.reactions = True
intents.messages = True
bot = discord.Client(intents=intents)
prefix = ""
@bot.event
async def on_ready():
print(f'We have logged in as {bot.user}')
await bot.change_presence(activity=discord.Activity(
type=discord.ActivityType.watching, name="test"
))
#Heads Or Tails
@bot.event
async def on_message(message):
if message.content.startswith(prefix + 'coinflip'):
headortails = random.randrange(1, 3)
if headortails == int(1):
await message.channel.send('heads')
elif headortails == int(2):
await message.channel.send('tails')
else:
await message.channel.send('Error random module malfunctioned')
bot.run('Token')
ohw
in my bot event?
u can pass message ids tho
!d discord.TextChannel.history use this to get channel's messages
async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)```
Returns an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator "(in Python v3.11)") that enables receiving the destinationโs message history.
You must have [`read_message_history`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") to do this.
Examples
Usage...
limit=10
ye
Like this?
#Heads Or Tails
@bot.event
async def on_message(message):
await bot.process_commands(message)
if message.content.startswith(prefix + 'coinflip'):
headortails = random.randrange(1, 3)
if headortails == int(1):
await message.channel.send('heads')
elif headortails == int(2):
await message.channel.send('tails')
else:
await message.channel.send('Error random module malfunctioned')
yes
stil not responding
demn u smort
hmmmmmmmm, something prob with intents then
intents = discord.Intents.default()
intents.message_content = True
intents.presences = True
intents.dm_typing = True
intents.bans = True
intents.dm_messages = True
intents.dm_typing = True
intents.guild_messages = True
intents.members = True
intents.typing = True
intents.reactions = True
intents.messages = True
bot = discord.Client(intents=intents)
should be good isnt it?
yes in my terminal its says: We have logged in as Community Bot#...
hmmmmmmmmmmm
do u have multiple on_message event?
I have other commands with on_message
yeaaaaaaaaaaaa
that causing the prob
change @bot.event to @bot.listen()
like *... not slash command
but u didnt add any prefix here?
uh what??
after the intents I have prefix = "*"
import discord
import random
import asyncio
#Perms
intents = discord.Intents.default()
intents.message_content = True
intents.presences = True
intents.dm_typing = True
intents.bans = True
intents.dm_messages = True
intents.dm_typing = True
intents.guild_messages = True
intents.members = True
intents.typing = True
intents.reactions = True
intents.messages = True
bot = discord.Client(intents=intents)
prefix = "*"
@bot.event
async def on_ready():
print(f'We have logged in as {bot.user}')
await bot.change_presence(activity=discord.Activity(
type=discord.ActivityType.watching, name="test"
))
#Heads Or Tails
@bot.listen
async def on_message(message):
await bot.process_commands(message)
if message.content.startswith(prefix + 'coinflip'):
headortails = random.randrange(1, 3)
if headortails == int(1):
await message.channel.send('heads')
elif headortails == int(2):
await message.channel.send('tails')
else:
await message.channel.send('Error random module malfunctioned')
#Bot Suggestions
@bot.event
async def on_message(message):
if message.content.startswith(prefix + 'suggest@'):
message_content3 = message.content
message_contentproccesed = message_content3.replace("*suggest@", "")
v = open("DCBotSuggestions.txt", "a")
v.write(" \n" + message_contentproccesed)
v.close
await message.channel.send(message_contentproccesed + " added")
if message.content.startswith('*readsugs'):
f = open("DCBotSuggestions.txt", "r")
readfile = f.read()
await message.channel.send(readfile)
f.close
#Bot Code
f = open('CommunityBot.py', 'r')
lines = f.readlines
f.close()
@bot.event
async def on_message(message):
if message.content.startswith(prefix + 'ScriptCodeDC'):
await message.channel.send(lines)
bot.run('TOken')
but u didnt set it up on bot=
This is al my code
bruh
hm?
@bot.listen()
AttributeError: 'Client' object has no attribute 'listen'
oh it's client :skul
then add await bot.process_commands(message) on all of em xd
after the def on message?
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").
still this error:
@bot.listen()
AttributeError: 'Client' object has no attribute 'listen'
change @bot.listen to @bot.event since it's to applicable on client obj
await bot.process_commands(message)
AttributeError: 'Client' object has no attribute 'process_commands'
that is the error if I type *coinflip
makes sense
@naive briar help em
Which one returns it
he is using discord.Client obj
async for message in tod_channel.history(limit=10)
async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)```
Returns an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator "(in Python v3.11)") that enables receiving the destinationโs message history.
You must have [`read_message_history`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") to do this.
Examples
Usage...
either channel id incorrect
or doesnt exists
or maybe it's returning string
tried printing info[0]?
!d discord.Guild.get_channel
get_channel(channel_id, /)```
Returns a channel with the given ID.
Note
This does *not* search for threads.
Changed in version 2.0: `channel_id` parameter is now positional-only.
xd
u r not even fetching info bruh
like
info=c.fetchone()
tf
how can a db work like dat ๐
u should add WHERE guild_id=a id
xd
but isn't he listing all guilds tho
idk xd
told if he want some specific guild
apparently he iterated through all guilds
The error explained everything
nahhh
No
embed.add_field(name="...", value="...")
Read the error
where did I say smth about custom ids?
^
The field needs a name
well, if you can't recognise that words are different...
There's a reason why you should know how to read tracebacks before touching discord.py
mutually
Which nobody cares about
I learnt to read tracebacks after 3 months of learning d.py (started python with it) โค๏ธ
Well, same for me
But reading tracebacks doesn't mean just read
almost anyone can read
They still watch football?
soccer*
why not xd
computer :are u sure about that
yes
gimme ur address
AIs are different stories
lemme break ur pc
OHHHHHHHHHH OK MAKES SENSE
tho they still are stupider than people
๐ซก
I mean, computers can read machine codes but most humans can't 
They're smort
I mean, that's their first language
silently laughing
binaryyyyy
<3
It's like saying that I know Russian and you dont
HAHA im smart
nah it's smort*
Noice ๐
im so sad
i have to delete the whole file
because a library that it's based on has become stupid or somehow broke
and i have commands that are using that file
๐ฅน
the sussy pdt library?
sussy?
ofcourse it was sus
what u talking bout
!pip parsedatetime
this
doesnt work and the ancient docs
Anyone know how to use from discord import Fileand the import easy_pil
what
yeah, doesn't work(
you want to send an image created by easy-pil as a file?
show code
Can in dm I don't want to leak it
leak what?
The code
bruv
I kinda worked hard on it lmao
which lib are u using?
Sent
It's alright
why discord\
The message is sent but the image is not
You are using @bot.slash_command ? @slate swan
ok yeah you should read what the error says
cuz the error says so, look at the warning lol
they are using nextcord but have discord installed
without any errors?
? yes
removed discord from requirements and clear your cache in the host
yeah "do0ing"
Yes no errors at all unless after 3 minutes or something it gives this error
discord.errors.HTTPExecption: 413 Played Too Large (error code: 40 005) Request entity too Large
you dont need to worry about grammar im the indian guy here
indians make grammar mistakes?
the image generated is oversize, reduce it's size by simple PIL image resize
im silent
I tried to make it instead of 1.2mb to 900kb and still not working
everyone does but meh
meh?
the final image?
The image on the bot folder
meh as in me
resize the final image
the image on the bot folder is ur current image
What size should I use
i told u earlier xd
but i see me in meh
What should I set it to
anything sendable
do0ing*
U can check the current size on the dm
try printing the size first
Idk actually
save the file locally first and check the size
mah bad
Bruh still same @slate swan
I keep resizing it smaller
Dude I made everything size 100 and still not working lmao
Even size of everything is 50 now
Bruh
Even size 20 not working.....
2022-12-18 15:42:34 ERROR discord.client Ignoring exception in on_member_join
Traceback (most recent call last):
File "/data/user/0/ru.iiec.pydroid3/files/arm-linux-androideabi/lib/python3.9/site-packages/discord/client.py", line 409, in _run_event
await coro(*args, **kwargs)
File "<string>", line 64, in on_member_join
File "/data/user/0/ru.iiec.pydroid3/files/arm-linux-androideabi/lib/python3.9/site-packages/discord/abc.py", line 1536, in send
data = await state.http.send_message(channel.id, params=params) File "/data/user/0/ru.iiec.pydroid3/files/arm-linux-androideabi/lib/python3.9/site-packages/discord/http.py", line 744, in request
raise HTTPException(response, data)
discord.errors.HTTPException: 413 Payload Too Large (error code: 40005): Request entity too large
This is the error @shrewd fjord @slate swan
!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.
is there a discord.guild.get_member_by_id? or something?
I'm getting this error
Traceback (most recent call last):
File "C:\Users\Admin\AppData\Roaming\Python\Python310\site-packages\disnake\ext\commands\common_bot_base.py", line 416, in _load_from_module_spec
spec.loader.exec_module(lib) # type: ignore
File "<frozen importlib._bootstrap_external>", line 883, in exec_module
File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
File "c:\Users\Admin\Desktop\Avalian\cogs\config.py", line 7, in <module>
class Config(Cog):
File "c:\Users\Admin\Desktop\Avalian\cogs\config.py", line 69, in Config
async def set_autorole_role(self, ctx: Context, role: Role):
File "C:\Users\Admin\AppData\Roaming\Python\Python310\site-packages\disnake\ext\commands\core.py", line 1371, in decorator
result = command(name=name, cls=cls, *args, **kwargs)(func)
File "C:\Users\Admin\AppData\Roaming\Python\Python310\site-packages\disnake\ext\commands\core.py", line 1631, in decorator
raise TypeError("Callback is already a command.")
TypeError: Callback is already a command.
Callback is already a command!
even though I don't have another command with the same name
!d discord.Guild.get_member
get_member(user_id, /)```
Returns a member with the given ID.
Changed in version 2.0: `user_id` parameter is now positional-only.
do you have another command named set_autorole_role ?
you probably used the @commands.command decorator twice
nah i just waited 5 mins, ran the bot again and it works ๐ฟ
@slate swan
Im new to json databases and idk the error here:
#code:
users[author] = str(author)
users[str(author)]['Wallet'] = str(0)
users[author]['Bank'] = 0
#err
Traceback (most recent call last):
File "/home/runner/uNomics/venv/lib/python3.8/site-packages/discord/app_commands/commands.py", line 862, in _do_call
return await self._callback(interaction, **params) # type: ignore
File "main.py", line 59, in balance
await open_account(int(author))
File "main.py", line 77, in open_account
users[str(author)]['Wallet'] = str(0)
TypeError: 'str' object does not support item assignment
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/runner/uNomics/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/uNomics/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/uNomics/venv/lib/python3.8/site-packages/discord/app_commands/commands.py", line 876, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'bal' raised an exception: TypeError: 'str' object does not support item assignment
this is json database or just json file
file i think
i made a file called mainbank.json
what is type of author variable
str
so users[author] = str(author)
but im not sure what to conbert it ot
is just having value same as key
yes
so what is the point of that
wdym by thus
are u storing it on author name or author id or
id
ok so ur data is structured like ```py
{"id": {"Wallet": 0}}
so you should do ```py
users[author_id] = {"Wallet": 0}
users[author_id] = {"Wallet": 0, "Bank": 0}
``` and u can do both like that
nvm actually
i think i got it
wait no i dont
ok so the traceback:
Traceback (most recent call last):
File "/home/runner/uNomics/venv/lib/python3.8/site-packages/discord/app_commands/commands.py", line 862, in _do_call
return await self._callback(interaction, **params) # type: ignore
File "main.py", line 62, in balance
wallet_amt = users[author]['Wallet']
KeyError: 'Wallet'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/runner/uNomics/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/uNomics/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/uNomics/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 'bal' raised an exception: KeyError: 'Wallet'
and the lines
wallet_amt = users[author]['Wallet']
bank_amt = users[author]['Bank']
ok so users[author] is a dict which doesnt have Wallet key in it
ok
so you can add Wallet key to that dict or write some code to handle the case where the dict does not have Wallet key (using try-except or if statments)
if i used the code you sent above, than shouldn't the key exisit
yes, but are u using it back to back
!e ```py
users = {}
users["0"] = {"Wallet": 0, "Bank": 0}
author = "0"
print(users[author]["Wallet"])
@meager chasm :white_check_mark: Your 3.11 eval job has completed with return code 0.
0
If thats basically what I a doing, sgouldn;t my code work>
so thats probably not what ur doing
file size should be less than 8mbs, just check for that
File "main.py", line 65, in balance
users_name = await client.get_user(author)
TypeError: object NoneType can't be used in 'await' expression
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/runner/uNomics/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/uNomics/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/uNomics/venv/lib/python3.8/site-packages/discord/app_commands/commands.py", line 876, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'bal' raised an exception: TypeError: object NoneType can't be used in 'await' expression
get_user is not coroutine
u dont await it
oh k
get_user should not be awaited, and its returning nOne for you for some reason lol
and if get_user is returning None then author is not valid id or it not in the cache
if ur sure its valid id then you can try with fetch_user
make sure the id is an int
tysm
nobody cares
Can you edit that for me you already have the code in dms
Because I tried a lot but it is still not working
yep i can do that for you, will just take a few time cuz im not home rn
Alright
I'll send the picture as well if you need
what should i do if i get this error discord.app_commands.errors.CommandInvokeError: Command 'test' raised an exception: TypeError: 'NoneType' object is not subscriptable
i created this py elif TypeError: await interaction.response.send_message(content="This user does not have an account yet!") return but now this wont get printed ```py
cursor.execute(f"SELECT name FROM profile WHERE id = {user.id}")
nameB = cursor.fetchone()
cursor.execute(f"SELECT age FROM profile WHERE id = {user.id}")
ageB = cursor.fetchone()
cursor.execute(f"SELECT region FROM profile WHERE id = {user.id}")
regionB = cursor.fetchone()
cursor.execute(f"SELECT interest FROM profile WHERE id = {user.id}")
interestB = cursor.fetchone()
cursor.execute(f"SELECT about FROM profile WHERE id = {user.id}")
aboutB = cursor.fetchone()
embed = discord.Embed(title=f"{user.name}'s profile:", color=color)
embed.add_field(name="Name:", value=nameB[0], inline=True)
embed.add_field(name="Age:", value=ageB[0], inline=True)
embed.add_field(name="From:", value=regionB[0], inline=True)
embed.add_field(name="Interests:", value=interestB[0], inline=False)
embed.add_field(name="About me:", value=aboutB[0], inline=False)
embed.set_thumbnail(url=user.display_avatar)
await interaction.response.send_message(content="Works", embed=embed)```
use try except statements for error handling, not conditionals
!sql-fstring
SQL & f-strings
Don't use f-strings (f"") or other forms of "string interpolation" (%, +, .format) to inject data into a SQL query. It is an endless source of bugs and syntax errors. Additionally, in user-facing applications, it presents a major security risk via SQL injection.
Your database library should support "query parameters". A query parameter is a placeholder that you put in the SQL query. When the query is executed, you provide data to the database library, and the library inserts the data into the query for you, safely.
For example, the sqlite3 package supports using ? as a placeholder:
query = "SELECT * FROM stocks WHERE symbol = ?;"
params = ("RHAT",)
db.execute(query, params)
Note: Different database libraries support different placeholder styles, e.g. %s and $1. Consult your library's documentation for details.
See Also
โข Python sqlite3 docs - How to use placeholders to bind values in SQL queries
โข PEP-249 - A specification of how database libraries in Python should work
also maybe use aiosqlite instead
Who ping :(
@deep sorrel
!intents
Using intents in discord.py
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. Various features of discord.py rely on having particular intents enabled, further detailed in its documentation. Since discord.py v2.0.0, it has become mandatory for developers to explicitly define the values of these intents in their code.
There are standard and privileged intents. To use privileged intents like Presences, Server Members, and Message Content, you have to first enable them in the Discord Developer Portal. In there, go to the Bot page of your application, scroll down to the Privileged Gateway Intents section, and enable the privileged intents that you need. Standard intents can be used without any changes in the developer portal.
Afterwards in your code, you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:
from discord import Intents
from discord.ext import commands
# Enable all standard intents and message content
# (prefix commands generally require message content)
intents = Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see discord.py's related guide, and for general information about them, see the Discord developer documentation on intents.
yes?
sorry
thanks
I do well, how do you do?
doing excellent thanks
!d discord.Interaction.original_response
await original_response()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Fetches the original interaction response message associated with the interaction.
If the interaction response was a newly created message (i.e. through [`InteractionResponse.send_message()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.InteractionResponse.send_message "discord.InteractionResponse.send_message") or [`InteractionResponse.defer()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.InteractionResponse.defer "discord.InteractionResponse.defer"), where `thinking` is `True`) then this returns the message that was sent using that response. Otherwise, this returns the message that triggered the interaction (i.e. through a component).
Repeated calls to this will return a cached value.
Yes
but, no solution
example /suggest message: hello
original_response doesn't need a message, it fetches the message
and later said: im = await interaction.original_response('Do you want upload image?, or say "N" to skip')
Before old: im = await interaction.send('Do you want upload image?, or say "N" to skip')
i see
you're probably looking for interaction.response.send, or a modal
exactly
maybe try moment idea.
@fading marlin
solution ok - and error again
send the traceback
error look
await interaction.response.send_message(f"{interaction.user.mention}, your suggestion has been successfully submitted! Check <#{exist_channels[1]}>")
Ah is original response no?
you have to replace that one with a followup, or edit the original message
Yes, loook image
await interaction.response.send_message(f"{interaction.user.mention}, your suggestion has been successfully submitted! Check <#{exist_channels[1]}>")
message2=await interaction.original_response()
you're still responding twice, you can't do that
hmm
followup
no remember lol.
!d discord.Interaction.followup
Returns the follow up webhook for follow up interactions.
it's a webhook
ah yes.
here look but but think.
there last "await message2.delete(delay=30)"
@fading marlin Ok
there is is correct: message2 = await interaction.original_response(f"{interaction.user.mention}, your suggestion has been successfully submitted! Check <#{exist_channels[1]}>") if is_cancelleds == True: return await message2.delete(delay=30)
Maybe try?
^
use a followup if you want to send another message after a response
ah, how is hmm
same "Interaction.followup"?
message2 = await interaction.Interaction.followup(f"{interaction.user.mention}, your suggestion has been successfully submitted! Check <#{exist_channels[1]}>")
no, Interaction is the class that has an instance property followup, interaction is an instance of Interaction
Hmmm
class discord.Webhook```
Represents an asynchronous Discord webhook.
Webhooks are a form to send messages to channels in Discord without a bot user or authentication.
There are two main ways to use Webhooks. The first is through the ones received by the library such as [`Guild.webhooks()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild.webhooks "discord.Guild.webhooks"), [`TextChannel.webhooks()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.TextChannel.webhooks "discord.TextChannel.webhooks"), [`VoiceChannel.webhooks()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.VoiceChannel.webhooks "discord.VoiceChannel.webhooks") and [`ForumChannel.webhooks()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.ForumChannel.webhooks "discord.ForumChannel.webhooks"). The ones received by the library will automatically be bound using the libraryโs internal HTTP session.
The second form involves creating a webhook object manually using the [`from_url()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Webhook.from_url "discord.Webhook.from_url") or [`partial()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Webhook.partial "discord.Webhook.partial") classmethods.
For example, creating a webhook from a URL and using [aiohttp](https://docs.aiohttp.org/en/stable/index.html "(in aiohttp v3.8)"):
webhooks have a send method
what?
you need update install discord py?
how
install discord.py...?
congratulations, you've installed dpy
thanks bro
๐
done solution maybe idea
and error "delete"?
Ok start on bot
send_message doesn't return anything
Nop, look
!d discord.InteractionResponse.send_message
await send_message(content=None, *, embed=..., embeds=..., file=..., files=..., view=..., tts=False, ephemeral=False, allowed_mentions=..., suppress_embeds=False, delete_after=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Responds to this interaction by sending a message.
Ya stop, same.
read image
original_response isn't the same as send_message
example same original_response next original_response
if you want to delete a message after a certain amount of time, see the delete_after kwarg in send_message
first: send_message -> second original_response three original_response?
ahh hmm
moment ok check remember
what?
@fading marlin await interaction.response.send_message(f"{interaction.user.mention}, your suggestion has been successfully submitted! Check <#{exist_channels[1]}> delete_after=5.0")
correct?
you haven't enabled message content intents in the dev portal
sure
No is bad
await interaction.response.send_message(f"{interaction.user.mention}, your suggestion has been successfully submitted! Check <#{exist_channels[1]}>, delete_after=5.0") think bad
error: discord.app_commands.errors.CommandInvokeError: Command 'suggest' raised an exception: TypeError: send_message() got an unexpected keyword argument 'delete_after'
No solution 
update your dpy
No ya have already
Why " is wrapping dlt after
Me watching fifa
Busy
is there await interaction.response.send_message(f"{interaction.user.mention}, your suggestion has been successfully submitted! Check <#{exist_channels[1]}>", delete_after=5.0)
you have to update it py -3 -m pip install -U discord.py
yes
apparently you don't
!d discord.InteractionResponse.send_message
await send_message(content=None, *, embed=..., embeds=..., file=..., files=..., view=..., tts=False, ephemeral=False, allowed_mentions=..., suppress_embeds=False, delete_after=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Responds to this interaction by sending a message.
original_response doesn't take any params, and you have to update your dpy
ya have -.-
omg god ._.
???
Can anyone tell me what's the problem here
error?
!intents - you don't have the message content intent enabled in the dev portal
Using intents in discord.py
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. Various features of discord.py rely on having particular intents enabled, further detailed in its documentation. Since discord.py v2.0.0, it has become mandatory for developers to explicitly define the values of these intents in their code.
There are standard and privileged intents. To use privileged intents like Presences, Server Members, and Message Content, you have to first enable them in the Discord Developer Portal. In there, go to the Bot page of your application, scroll down to the Privileged Gateway Intents section, and enable the privileged intents that you need. Standard intents can be used without any changes in the developer portal.
Afterwards in your code, you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:
from discord import Intents
from discord.ext import commands
# Enable all standard intents and message content
# (prefix commands generally require message content)
intents = Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see discord.py's related guide, and for general information about them, see the Discord developer documentation on intents.
I can change this or not
leave that as-is
reset your token
you're leaking your token
๐คฆ don't leak your token, it can cause serious damage
it should've been invalidated for you now
Yea
I've already told you how to fix your issue, and you're leaking your token again
this test bot
literally read the last 2 lines of the error
so i renamed a slash command and its not showing up ? how long can it take to show up ?
sync
huh ?
sync your command tree
how ?
!d discord.app_commands.CommandTree.sync
await sync(*, guild=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Syncs the application commands to Discord.
This also runs the translator to get the translated strings necessary for feeding back into Discord.
This must be called for the application commands to show up.
bot.tree.sync or whatever
ah ok
Hello everyone, good afternoon.
How can i disable all buttons in a class?
Is there any method for this?
Follow the command:
Hey @full marten!
It looks like you tried to attach a Python file - please use a code-pasting service such as https://paste.pythondiscord.com
Or has another way for disable all buttons?
usually i create my own custom view subclass with extra features like disable all buttons and whatnot
you just loop through discord.ui.View.children and .disable=True all of them
a for loop?
Could you send me an example? @sick birch
yes a for loop
for child in <instance>.children:
... # disable `child` here
Do you create a function in a class what does it do?
Or use an instance of the class
sure you can create a disable_all method in your ui.View subclass if you want
hm
could i do it like this?
of course
class MyView(discord.ui.View):
def __init__(...):
...
def disable_all(...):
for child in self.children:
child.disabled = True
Oh, i understand now
I did it like that and doesn't work
def disable_all(self):
for child in self.children:
child.disabled = True
you have to update the view again afterwards for it to visually update.
"Interaction failed", so it says
what?
I didn't understand
Resend the view basically
after you set button.disabled to true, you have to edit your message containing the view and pass something like view=self
Or edit your original message with the new view (self)
!d discord.Interaction.edit_original_response
await edit_original_response(*, content=..., embeds=..., embed=..., attachments=..., view=..., allowed_mentions=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Edits the original interaction response message.
This is a lower level interface to [`InteractionMessage.edit()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.InteractionMessage.edit "discord.InteractionMessage.edit") in case you do not want to fetch the message and save an HTTP request.
This method is also the only way to edit the original message if the message sent was ephemeral.
Oh yes, yes
I had forgotten
Are you responding to the interaction?
Is it possible to do guild.get_member(id) but for multiple users at once?
memberlist = [1,2,3,4,5]
member_id_list = guild.get_member(memberlist)
no, you have to get each member independently
.get_member is O(1) so it's about as fast as it gets :)
Don't worry about performance bottleneck there
fetch_member is another story
member_id_list= [1,2,3,4,5]
members = list(map(guild.get_member, member_id_list))
Im just checking if my code is right but would the or be right in this? {cmd.signature.replace('=None' or '=new role', '')}
"=None" will always evaluate to True, so you'll always get cmd.signature.replace("=None", "")
you'd have multiple .replaces
you're welcome
!d discord.Client.get_guild
get_guild(id, /)```
Returns a guild with the given ID.
Changed in version 2.0: `id` parameter is now positional-only.
you need the full namespace
you're using a class when you should be using an instance
get_guild isn't a coroutine either
Good luck
Best of luck!
@app_commands.command(name = "download", description="Download Files")
async def download(self, interaction: discord.Interaction, name:str) -> None:
How do I make name:str optional?
i keep gettng this error when i run my bot Traceback (most recent call last): File "c:\Users\jonah\Downloads\Dev\turtle_1.py", line 51, in <module> client.run(os.environ['Bot token']) ~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "<frozen os>", line 678, in __getitem__ KeyError: 'Bots token' Inside of "Bots token" is the actual token jus not gonna keep the token there
name:str = None
Just do
client.run('your bot token')
Hey, any idea on how to use this Apps feature when you click on messages or documentation on it?
Context menus
Thx
Hmm doing something silly wrong and not sure why. In a app command, I send a response with a view that has a dropdown through the decorator. In the dropdown callback, it tries to call Interaction.edit_original_response() but I get NotFound and invalid webhook. Why?
That method is used to edit the interaction's response message
You need to send a response message to use that method
(I think
)
@client.event
async def on_ready():
async with aiosqlite.connect("main.db") as db:
async with db.cursor() as cursor:
await cursor.execute('CREATE TABLE IF NOT EXISTS users (prefix STRING, id INTEGER, ad STRING, guild INTEGER, welcomechannel INTEGER, adchannel INTEGER, welcomemessage STRING, leavemessage STRING, announcechannel INTEGER, addelete)')
await db.commit()
print(f"logged in as {client.user}")
await status()
Traceback (most recent call last):
File "/home/runner/idk-bot/venv/lib/python3.8/site-packages/discord/client.py", line 409, in _run_event
await coro(*args, **kwargs)
File "main.py", line 34, in on_ready
await db.commit()
File "/home/runner/idk-bot/venv/lib/python3.8/site-packages/aiosqlite/core.py", line 162, in commit
await self._execute(self._conn.commit)
File "/home/runner/idk-bot/venv/lib/python3.8/site-packages/aiosqlite/core.py", line 67, in _conn
raise ValueError("no active connection")
ValueError: no active connection
ok thank you
async def get_prefix(client, message):
async with aiosqlite.connect("main.db") as db:
async with db.cursor() as cursor:
await cursor.execute('SELECT prefix FROM users WHERE guild = ?', (message.guild.id,))
prefix = cursor.fetchone()
if prefix:
prefix = prefix[0]
else:
prefix = "*" #return default prefix if guild not saved in database.
db.close()
return prefix
File "/home/runner/idk-bot/venv/lib/python3.8/site-packages/discord/client.py", line 409, in _run_event
await coro(*args, **kwargs)
File "/home/runner/idk-bot/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 1394, in on_message
await self.process_commands(message)
File "/home/runner/idk-bot/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 1389, in process_commands
ctx = await self.get_context(message)
File "/home/runner/idk-bot/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 1288, in get_context
prefix = await self.get_prefix(origin)
File "/home/runner/idk-bot/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 1195, in get_prefix
ret = await discord.utils.maybe_coroutine(prefix, self, message) # type: ignore
File "/home/runner/idk-bot/venv/lib/python3.8/site-packages/discord/utils.py", line 662, in maybe_coroutine
return await value
File "main.py", line 15, in get_prefix
prefix = prefix[0]
TypeError: 'coroutine' object is not subscriptable
/home/runner/idk-bot/venv/lib/python3.8/site-packages/discord/client.py:416: RuntimeWarning: coroutine 'Cursor.fetchone' was never awaited
pass
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
Await fetchone
await cursor.execute("UPDATE users SET prefix = ? WHERE guild = ?", (text, ctx.guild.id,))
old = await cursor.fetchone()
pr = discord.Embed(title='prefix changed!')
pr.add_field(name='Old Prefix:', value=old[0])
File "/home/runner/idk-bot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 229, in wrapped
ret = await coro(*args, **kwargs)
File "main.py", line 87, in setprefix
pr.add_field(name='Old Prefix:', value=old[0])
TypeError: 'NoneType' object is not subscriptable
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/runner/idk-bot/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 1349, in invoke
await ctx.command.invoke(ctx)
File "/home/runner/idk-bot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 1023, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
File "/home/runner/idk-bot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 238, in wrapped
raise CommandInvokeErr
or(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: 'NoneType' object is not subscriptable
try only do value=old
i think it doesnt returns list
idk what db u using tho lol
the UPDATE statement by itself doesnt return any row you can fetch afterwards
anyone know why my unban command doesnt work? @client.command() async def unban(ctx, user: discord.User): await ctx.guild.unban(user) await ctx.send(f'{user} has been unbanned from the server.')
Hey I am trying to get a users avatar using message.author.avatar_url down here in the embed but for some reason I get this error:
AttributeError: 'User' object has no attribute 'avatar_url' and I can't figure out how to fix it :/
My code:
# Trigger when bot gets DMed
@client.listen()
async def on_message(message):
if message.channel.type == discord.ChannelType.private: # Check if the message is DM
if message.author == client.user:
pass
else:
channel = client.get_channel(CHANNEL_ID) # Channel to send DMs in
print(f"[DM] Got a DM from {message.author.display_name}#{message.author.discriminator}")
# Send the message in the channel
embed = discord.Embed(description=message.content, color=0xffffff)
embed.set_author(name=f"{message.author.display_name}#{message.author.discriminator} ({message.author.id})", icon_url=message.author.avatar_url)
embed.set_footer(text="Received by DM")
await channel.send(embed=embed)
it's avatar.url
and better use display_avatar instead of avatar since avatar could return None in case of a discord default avatar
any idea how to like set chanel in guild for something?
like /set-log #channel
and put it in a json database
yes just edit the json file
but still use a proper database for this
don't use a json file really
I see, thanks a lot <3
csv?
use something like sqlite (small bots) or postgresql (recommended)
also got the docs for this?
csv is also not the best
sqlite is a local db am i right?
Oh and if I want the url for thet display_avatar do I need to use display_avatar.url?
yeah
yeah sure
Oki!
^
you can just learn how to use json
if you wanna learn sql then -> https://sqlbolt.com/
SQLBolt provides a set of interactive lessons and exercises to help you learn SQL
ok
๐ซ
both of them returns url btw
Noted
I have forked a project from GitHub how to install it's dependencies from poetry.lock file?
you're going to need python-poetry.
It created a virtual env for dependencies
that is what it does yes
But how can I use it in current project?.
assuming you're in the directory you can use poetry shell to spawn a subprocess that sources the venv
This has probably been asked a lot but i cant find anything on it anyone know if there is a way to change a discord bots avatar from a URL?
I done and it gives spawning shell.....
But not using dependencies in current directory
Now what to do?
assuming we are using discord.py, you can give ClientUser.edit with the avatar kwarg with bytes
I'm unsure what you're talking about.
What to do after running 'poetry shell' command in current working directory
?
you use it like you normally would?
I recommend you read the Python documentation on virtual environments.
i am using discord.py but im very new so im ngl u have 0 clue what kwarg is, I tried using
response = requests.get(URL)
avatar = response.content
await client.user.edit(avatar=avatar)
but that just resulted in the bots avatar not changing and not throwing any errors
Wdym
read this: https://docs.python.org/3/library/venv.html
you likely need to read the response
like
with open('name.png', 'wb') as f:
f.write(avatar)
f.close()
?
how would i do that if you dont mind me asking? im extremally new just been using google to try and figure everything out lol
oh wait so like response.content instead of where i added avatar?
property content```
Content of the response, in bytes.
wdym?
I tried running
response = requests.get('https://static.wikia.nocookie.net/marvel_dc/images/f/f1/Raven_Earth-Teen_Titans_002.jpg/revision/latest/scale-to-width-down/350?cb=20080424010459')
with open(response.content, 'rb') as f:
read_response = f.read(response.content)
await client.user.edit(avatar=read_response)
f.close()
and i got the error: UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byteโ[0m... Am i on the right track?
Why
It's just
await client.user.edit(avatar=response.content)
!d discord.ClientUser.edit
await edit(*, username=..., avatar=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Edits the current profile of the client.
Note
To upload an avatar, a [bytes-like object](https://docs.python.org/3/glossary.html#term-bytes-like-object "(in Python v3.11)") must be passed in that represents the image being uploaded. If this is done through a file then the file must be opened via `open('some_filename', 'rb')` and the [bytes-like object](https://docs.python.org/3/glossary.html#term-bytes-like-object "(in Python v3.11)") is given through the use of `fp.read()`.
The only image formats supported for uploading is JPEG and PNG.
Changed in version 2.0: The edit is no longer in-place, instead the newly edited client user is returned...
you are amazing i swear I did this but ig not
thank you so much
omg im so stupid this was the first thing i did earlier but rather than grabbing the user's avatar that i wanted it was grabbing its own so it never actually changed the avatar
error "discord.app_commands.errors.CommandInvokeError: Command 'suggest' raised an exception: TypeError: original_response() takes 1 positional argument but 2 were given"
await interaction.original_response(f"{interaction.user.mention}, your suggestion has been successfully submitted! Check <#{exist_channels[1]}>")
First: im = await interaction.response.send_message('Do you want upload image?, or say **"N"** to skip') - Second: await interaction.original_response(f"{interaction.user.mention}, your suggestion has been successfully submitted! Check <#{exist_channels[1]}>")
Interaction.original_response do not take arguments
!d discord.Interaction.original_response
await original_response()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Fetches the original interaction response message associated with the interaction.
If the interaction response was a newly created message (i.e. through [`InteractionResponse.send_message()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.InteractionResponse.send_message "discord.InteractionResponse.send_message") or [`InteractionResponse.defer()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.InteractionResponse.defer "discord.InteractionResponse.defer"), where `thinking` is `True`) then this returns the message that was sent using that response. Otherwise, this returns the message that triggered the interaction (i.e. through a component).
Repeated calls to this will return a cached value.
yes but mention user + channel
._.
hmm
maybe try interaction.response.send_message ?
What
What???
read error?
What is interaction.interaction??
hmm
i see forget sigh 
done fix.
moment check.
look "This interaction has already been responded to before"
You can't respond to the interaction twice
yes, how solution..
remember before up:
Don't respond to it twice?
no cant 2 arguments
2 times like this because he did understand but that added original_response that I can't 2 arguments did you understand?
maybe only 1
not 2 correct?
What are you even trying to do
.
read there and await interaction.original_response(f"{interaction.user.mention}, your suggestion has been successfully submitted! Check <#{exist_channels[1]}>")
What does that supposed to mean
..
I seriously didn't understand you? Why is it mentioning user and channel? Why can't I? It has 1 and 2 arguemtns. Is that original_response?
Because how many times thousands without understanding what is it about? I read there 1 and 2 arguments as I need to "mention and channel" but I can't so I'm not good at English and my Spanish and deaf and disability
But what is that I give an example.
You want to edit the response?
yeah
!d discord.Interaction.edit_original_response
await edit_original_response(*, content=..., embeds=..., embed=..., attachments=..., view=..., allowed_mentions=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Edits the original interaction response message.
This is a lower level interface to [`InteractionMessage.edit()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.InteractionMessage.edit "discord.InteractionMessage.edit") in case you do not want to fetch the message and save an HTTP request.
This method is also the only way to edit the original message if the message sent was ephemeral.
ah there last "edit"?
i see.
error "discord.app_commands.errors.CommandInvokeError: Command 'suggest' raised an exception: TypeError: edit_original_response() takes 1 positional argument but 2 were given"
same 1 and 2 aruugemnt.
It's keyword-only argument method
i see, there you code to fix? await interaction.edit_original_response(f"{interaction.user.mention}, your suggestion has been successfully submitted! Check <#{exist_channels[1]}>")
It's just edit_original_response(content=...) ๐คท
ahh
ya remember content=
No idea much sigh.
"content (Optional[str]) โ The content to edit the message with or None to clear it."
there is correct?
ok solution done @naive briar
thx
Why isnt my bot registered my new commands?
Text or slash
slash
i got 19 (and 1 unsynced) command, and none are belong to the new command I just made
Did you sync the command tree
async def setup_hook(self):
for filename in os.listdir("./cogs"):
if filename.endswith(".py"):
await self.load_extension(f"cogs.{filename[:-3]}")
await bot.tree.sync()
``` this runs on startup so yes
I never had an issue before
You have to wait a bit for the commands to show up if you sync globally
In the past the commands would show up and update basically in real time
Well..
While I wait for the command to pop on up, wanna see the command and see if I did anything wrong?
I cant test it to find out :/
anyone there
No

We care. We love. We cherish every one of you.
i am runnning a bot having moderation,ping and embed on prefixes now i want to implement them with slash commands
No question is too stupid.
we just kidnap ppl
mod ....... lol
Are you using the latest discordpy?
yes
You need to use app_commands
all embed,moderation and ping are in cog
here's a nice guide for slash cmds
i just wat to implement them in cogs
async example(commands.Cog):
#init here
@app_commands.command(name="test", description="test")
async def test(self, interaction:discord.Interaction):
await interaction.response.send_message("test complete")
Lol
i get it
Lemme see this
there is lot of reading dat
i havent seen it before ๐ค
data
import discord
from discord.ext import commands
class Moderation(commands.Cog):
def __init__(self, client):
self.client = client
@commands.Cog.listener()
async def on__ready(self):
print(f"{self.__class__.__name__} Cog has been loaded\n-----")
@commands.command()
@commands.guild_only()
@commands.has_guild_permissions(ban_members=True)
async def kick(self, ctx, member: discord.Member, *, reason=None):
await ctx.guild.kick(user=member, reason=reason)
embed = discord.Embed(title=f"{ctx.author.name} has kicked {member.name}", description=reason,color = discord.Color.random())
await ctx.send(embed=embed)
@commands.command()
@commands.guild_only()
@commands.has_guild_permissions(ban_members=True)
async def ban(self, ctx, member: discord.Member, *, reason=None):
await ctx.guild.ban(user=member, reason=reason)
embed = discord.Embed(title=f"{ctx.author.name} has banned {member.name}", description=reason,color = discord.Color.random())
await ctx.send(embed=embed)
@commands.command()
@commands.guild_only()
@commands.has_guild_permissions(ban_members=True)
async def unban(self, ctx, member, *, reason=None):
member = await self.client.fetch_user(int(member))
await ctx.guild.unban(member, reason=reason)
embed = discord.Embed(title=f"{member.name} has been Unbanned", description=reason,color = discord.Color.random())
await ctx.send(embed=embed)
@commands.command()
@commands.guild_only()
@commands.has_guild_permissions(manage_messages=True)
async def purge(self, ctx, amount=15):
await ctx.channel.purge(limit=amount+1)
embed = discord.Embed(title=f"{ctx.author.name} purged: {ctx.channel.name}", description=f"{amount} messages were cleared",color = discord.Color.random())
await ctx.send(embed=embed)
async def setup(client):
await client.add_cog(Moderation(client))
why would you send that
how to change them so that i can use them with slash commands and prefix
use hybrid commands
just import from discord import app_commands
and change @commands.command() to @app_commands.command(name="this", description="description")
change all .command() to .hybrid_command() , thats all ig
oh thanks
or if u want both slash and text commands, use hybrid obviously
i need to import them right
discord.ext.commands
you already have it imported
async def process_dms(self):
await self.bot.wait_until_ready()
with await self.bot.redis as r:
while True:
req = await r.blpop("send_dm")
uid, content = pickle.loads(req[1])
self.bot.loop.create_task(self.bot.send_dm(uid, content))
let me try now
What even is with await
Traceback (most recent call last):
File "/home/runner/funny-bot-4/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 190, in wrapped
ret = await coro(*args, **kwargs)
File "main.py", line 1264, in logs
file.write(f"{msg.channel.category} - {msg.channel.name}\n{msg.created_at} - {msg.author.display_name}: {msg.clean_content}\n")
AttributeError: 'File' object has no attribute 'write'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/runner/funny-bot-4/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 1347, in invoke
await ctx.command.invoke(ctx)
File "/home/runner/funny-bot-4/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 986, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
File "/home/runner/funny-bot-4/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 199, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'File' object has no attribute 'write'
.redis is None
don't use while True loop
don't use bot.loop.create_task
@client.command()
async def logs(ctx):
c = client.get_channel(1031746508980224010)
for channel in ctx.guild.text_channels:
fileName = f"{channel.name}.txt"
with open(fileName, "w") as file:
async for msg in channel.history(limit=None):
file.write(f"{msg.channel.category} - {msg.channel.name}\n{msg.created_at} - {msg.author.display_name}: {msg.clean_content}\n")
file = discord.File(fileName)
await c.send(file=file)
idk maybe im just not educated enough, but pretty sure you cant use await in a while loop like that
after removing it shows same error
writeline/writelines?
what did you remove
while loop and bot.loop.create_task
both lines i removed
thanks guys it worked
you ignored the very first point @latent veldt
so what to do?
tell me
await client.tree.sync()do i still need to use this code
it was in my main file
yes
setup the redis variable properly
can you tel me what should i code for mute and unmute commands as well
I'll recommend using timeouts instead
!d discord.Member.timeout
await timeout(until, /, *, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Applies a time out to a member until the specified date time or for the given [`datetime.timedelta`](https://docs.python.org/3/library/datetime.html#datetime.timedelta "(in Python v3.11)").
You must have [`moderate_members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.moderate_members "discord.Permissions.moderate_members") to do this.
This raises the same exceptions as [`edit()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member.edit "discord.Member.edit").
....
this is the moderation file
take a discord.Member argument in your command
and use member.timeout(until)
where until is a datetime or timedelta
hello cnan someone help me ```py
nextcord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'dict' object has no attribute 'append'
```py
@client.command()
async def test1(ctx):
with open("test.json", "r") as f:
user_ids = json.load(f)
# Add the user's ID to the user_ids list
user_ids.append(ctx.author.id)
# Save the updated user ID data to the JSON file
with open("test.json", "w") as f:
json.dump(user_ids, f)
await ctx.channel.send("User ID added successfully!")
๐
ew nextcord
user_ids is a dictionary not a list
why is userids a dictionary anyway?
that will do but what are you actually trying to do in the cmd
because its a json loaded in form of dictionary?
this is a dictionary
the variable itself is regarded as a list
userids is part of a dictionary but when read it'll be a list
tryna learn json
if i was wrong this wouldnt work
doing something
how would that be useful for operations like ```py
{
"user1": 0,
"user2": 2
}
don't, json is not meant to be used a database
learn sql or a valid json like database like mongodb
it's terrible as a database system but great if you dont need a full database system
just learning:)
yes, its fine to store static data.
Also, a json file starts to get slow after like 100k lines or whatever
lemme check
I got a json file somewhere
i am trying to make my bot read the json file and then make an account for them.
also can async def be used like normal function?
nope
hmm
finally found the file!
just use if str(id) in user_ids.key() then, no need to convert to a list
400k lines is when you start to notice some major issues
eh
still works so why not.
it can get corrupted even at 10 lines if there's a simple recursion
lol
i've not had an issue yet
and I got like 30 of these files at 400k lines
Oh no, these files arent actively being used ๐
or something
yes
or if you want to output it to the console, print(json.dumps(mydict, indent=4))
what does this mean
we dont know how your bot works specifically but i'd guess ur using the on_message event
yes
url is a positional arg @slate swan
just match the user id with your database and return if its a mtch
how to solve
@client.event
async def on_message(message):
# Increment the user's experience points
user_id = str(message.author.id)
if user_id not in levels:
levels[user_id] = {"xp": 0, "level": 1}
levels[user_id]["xp"] += 1
# Check if the user has leveled up
xp = levels[user_id]["xp"]
level = levels[user_id]["level"]
if xp >= 2 * level:
levels[user_id]["level"] += 1
await message.channel.send(f"{message.author.mention} has leveled up to level {level + 1}!")
# Save the updated leveling data to the JSON file
with open("levels.json", "w") as f:
json.dump(levels, f)
swap them
!d discord.Embed.set_thumbnail
set_thumbnail(*, url)```
Sets the thumbnail for the embed content.
This function returns the class instance to allow for fluent-style chaining.
Changed in version 1.4: Passing `None` removes the thumbnail.
ok
its .format, not ,format
i think there's a is bot somewhere
dont use str.format
like ctx.author.bot?
Specifies if the user is a bot account.
message.author.bot
embed.set_thumbnail(url=member.avatar.url)
In your on_message command, just do a check if message.author.bot: return
no user shall use thy bot
still doesnt display tho
thanks
what version of discord.py are you even using
i think the latest
avatar_url has been removed from like 1.5years
python 2.1
how do i display the userโs avatar then
!d discord.Member.avatar
property avatar```
Equivalent to [`User.avatar`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User.avatar "discord.User.avatar")
like this? sales.set_thumbnail(discord.Member.avatar)
Can you edit them private messages? The ones that only show to you, with the blue background - can't remember what they're called (ephemeral or something lol) nevermind you can't
!d discord.Interaction.edit_original_response
await edit_original_response(*, content=..., embeds=..., embed=..., attachments=..., view=..., allowed_mentions=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Edits the original interaction response message.
This is a lower level interface to [`InteractionMessage.edit()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.InteractionMessage.edit "discord.InteractionMessage.edit") in case you do not want to fetch the message and save an HTTP request.
This method is also the only way to edit the original message if the message sent was ephemeral.
You can ๐คจ
"You also cannot edit the ephemeral state of a message, so ensure that your first response sets this correctly."
Ephemeral state
oh shit
That most likely means that you can't edit to a normal message
That everyone can see
Hello,
How would I go about getting a random message from a channel using / commands?
how do i put emoji in embeded
@commands.Cog.listener()
async def on_message(self, message: discord.Message):
if message.author.bot or message.guild is None:
return
ctx = await self.bot.get_context(message)
if ctx.valid:
return
current = time.time()
# Spamcheck, every one second
if current - self.bot.cooldown_users.get(message.author.id, 0) < 1.5:
return
self.bot.cooldown_users[message.author.id] = current
# Increase XP on selected pokemon
await self.increase_xp(message)
# Increment guild activity counter
if not message.guild:
return
if current - self.bot.cooldown_guilds.get(message.guild.id, 0) < 1:
return
self.bot.cooldown_guilds[message.guild.id] = current
self.bot.guild_counter[message.guild.id] = self.bot.guild_counter.get(message.guild.id, 0) + 1
spawn_threshold = 8 if message.guild.id == 793691412864434226 else 24
if self.bot.guild_counter[message.guild.id] >= spawn_threshold:
self.bot.guild_counter[message.guild.id] = 0
guild = await self.bot.mongo.fetch_guild(message.guild)
if len(guild.channels) > 0:
channel = message.guild.get_channel_or_thread(random.choice(guild.channels))
else:
channel = message.channel
if channel is None:
return
self.bot.loop.create_task(self.spawn_pokemon(channel))
getting error
Ignoring Exception on_message
!d discord.abc.Messageable.history
async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)```
Returns an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator "(in Python v3.11)") that enables receiving the destinationโs message history.
You must have [`read_message_history`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") to do this.
Examples
Usage...
any help?
what r u trying to accomplish
how do i add an emoji in an embed message
yo, how would I make a command accept a string as a variable without having to do quotes
@bot.command()
async def echo(ctx, message: str):
await ctx.send(message)
this doesnt work for me and i would've thought its this
just add a * before the message parameter
ctx: commands.Context, *, message: str
oh ty ๐
just add a * before the message parameter
ctx: commands.Context, *, message: str
a custom emoji?
there's some parts of embeds where that won't work
?

im trying to make my first discord bot at the moment
Any ideas on why this is not working?
@client.command
async def ping(ctx):
await ctx.send(f'Pong! {round(client.latency * 1000)}ms')```
Put two parentheses behind the @client.command like @client.command()
ok ty
@client.command()
async def ping(ctx):
await ctx.send(f'Pong! {round(client.latency * 1000)}ms')``` still doesnt work
bot doesnt send anything
import discord
from discord.ext import commands
client = commands.Bot(command_prefix = '.')
bot = discord.Client()
@bot.event
async def on_ready():
print('Bot Online!')
@client.command()
async def ping(ctx):
await ctx.send(f'Pong! {round(client.latency * 1000)}ms')
bot.run('removed for sending purposes')```
Bro
client = commands.Bot(command_prefix = '.')
bot = discord.Client()
Name variables correctly for god's sake, the confusion happened because of this
ok
!intents also this
Using intents in discord.py
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. Various features of discord.py rely on having particular intents enabled, further detailed in its documentation. Since discord.py v2.0.0, it has become mandatory for developers to explicitly define the values of these intents in their code.
There are standard and privileged intents. To use privileged intents like Presences, Server Members, and Message Content, you have to first enable them in the Discord Developer Portal. In there, go to the Bot page of your application, scroll down to the Privileged Gateway Intents section, and enable the privileged intents that you need. Standard intents can be used without any changes in the developer portal.
Afterwards in your code, you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:
from discord import Intents
from discord.ext import commands
# Enable all standard intents and message content
# (prefix commands generally require message content)
intents = Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see discord.py's related guide, and for general information about them, see the Discord developer documentation on intents.
Traceback (most recent call last):
File "c:\Users\PC\Desktop\Aleccy Bot\main.py", line 96, in <module>
bot.load_extension(f"cogs.{fn[:-3]}")
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\ext\commands\bot.py", line 888, in load_extension
self._load_from_module_spec(spec, name, extras=extras)
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\ext\commands\bot.py", line 769, in _load_from_module_spec
raise errors.ExtensionFailed(key, e) from e
nextcord.ext.commands.errors.ExtensionFailed: Extension 'cogs.cog' raised an error: ImportError: cannot import name 'Enum' from 'discord' (unknown location)```
is there a way one can update a json key for example
i have a json key that is
owner = [1234]
now i want to add one more id in it that's 5678 so that it becomes
owner = [1234,5678]
@naive briar :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | [1234]
002 | [1234, 5678]
:0 wow ty
like i dont have enum in my code
show code

