#discord-bots
1 messages · Page 145 of 1
is there a way to remove that black thing
thats where your spot is in the terminal
does anyone know how to make my bot not respond to commands sent in private message?
!d discord.ext.commands.guild_only
@discord.ext.commands.guild_only()```
A [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that indicates this command must only be used in a guild context only. Basically, no private messages are allowed when using the command.
This check raises a special exception, [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") that is inherited from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").
If used on hybrid commands, this will be equivalent to the [`discord.app_commands.guild_only()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.guild_only "discord.app_commands.guild_only") decorator. In an unsupported context, such as a subcommand, this will still fallback to applying the check.
I didn't really understand
@glad cradle
yes?
wassuP!
can we call?
Do you know how to make my discord bot unable to respond to commands executed in private message?
bro you can't remove that black cursor, maybe changing the vscode theme you could do something (I'm not sure)
you need to add
@commands.guild_only()
before the command function signature
e.g
from discord.ext import commands
...
@commands.command()
@commands.guild_only()
async def my_command(...):
...
it happens on cmd too?
yes
decorators aren't lego u cant just slap anything over it just client.command is enough also commands.guild_only() goes below that
this example is valid if you're inside cogs
and if im not?
@client.command()
@commands.guild_only()
...
as asher said
yes but if im not in cogs how i do?
Above your message
!ytdl
Per Python Discord's Rule 5, we are unable to assist with questions related to youtube-dl, pytube, or other YouTube video downloaders, as their usage violates YouTube's Terms of Service.
For reference, this usage is covered by the following clauses in YouTube's TOS, as of 2021-03-17:
The following restrictions apply to your use of the Service. You are not allowed to:
1. access, reproduce, download, distribute, transmit, broadcast, display, sell, license, alter, modify or otherwise use any part of the Service or any Content except: (a) as specifically permitted by the Service; (b) with prior written permission from YouTube and, if applicable, the respective rights holders; or (c) as permitted by applicable law;
3. access the Service using any automated means (such as robots, botnets or scrapers) except: (a) in the case of public search engines, in accordance with YouTube’s robots.txt file; (b) with YouTube’s prior written permission; or (c) as permitted by applicable law;
9. use the Service to view or listen to Content other than for personal, non-commercial use (for example, you may not publicly screen videos or stream music from the Service)
Hey guys, say I want to print database query results into an embed, how should I approach solving an embed being too big, and splitting into different pages for example.
@mellow verge, as you know this is for music. Music bots aren't allowed since they violate YouTubes Terms of Service.
These query results could be really of any length
!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...
ah can use length
so I guess if I devide the length by 6000 thats my number of pages
Well do know that titles etc also count towards it, and as for pages, use a button paginator preferably.
but how would I be able to create different amounts of pages and go between them
Do you have any experience in View/interactions?
I mean i just kind of came from discord.py v1 so Im still wrapping my head around v2 interactions, i used to use discord-interactions.py
I would have no issue if I knew the amount of pages I needed to create, I could easily make a button or react transition between them, just dont know how to approach an unknown page length
What is the content?
Does anyone know,
Does hosting a discord bot cause internet issues? Like could I host one from home or would it use up all the bandwidth
Nah
You can easily self host
Cool, thank you
looks like this
but there could be anywhere from none to.. a lot which I would limit to like 50 different results.
i undertsood
it works now
why are you calling the recieve so many times, its meant to be done only once within the _receiveevent ( that might be ghosting your events )
and do you update self.lasts everytime a dispatch happens?
to avoid crashing my bot I can't make a condition if command is in private message return "Command cant be used in private message" else: pass
!tag on_command_error
Whatever
Use an event call on_command_error
Example:
@bot.event
async def on_command_error(ctx,error):
if isinstance(error,commands.NoPrivateMessage):
await ctx.send("This command is guild only, you can't use it in direct message!")
discord.on_error(event, *args, **kwargs)```
Usually when an event raises an uncaught exception, a traceback is logged to stderr and the exception is ignored. If you want to change this behaviour and handle the exception for whatever reason yourself, this event can be overridden. Which, when done, will suppress the default action of printing the traceback.
The information of the exception raised and the exception itself can be retrieved with a standard call to [`sys.exc_info()`](https://docs.python.org/3/library/sys.html#sys.exc_info "(in Python v3.11)").
Note
`on_error` will only be dispatched to [`Client.event()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.event "discord.Client.event").
It will not be received by [`Client.wait_for()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.wait_for "discord.Client.wait_for"), or, if used, [Bots](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#ext-commands-api-bot) listeners such as [`listen()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.listen "discord.ext.commands.Bot.listen") or [`listener()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Cog.listener "discord.ext.commands.Cog.listener").
Changed in version 2.0: The traceback is now logged rather than printed.
Hi again and sorry for my disappointment but I still need help I don't understand why my order "c" is not recognized
just know that before asking for help in the server I search on stackorverflow but I do not find
@client.command()
I did it but now i can use the command in the server lol
i dont have any error message
You have a try-except. That cancels the error.
owhh ty
where
anyone knows?
Help me, please!
I wonder why it doesn't always fail, sometimes it works fine on the same code
how would i do that?
this smells like a replit moment (can only see half your error so i'm guessing it's a cloudflare ban)
tends to happen a lot on such hosts because they share IPs
hmm, wait me, i will try take all
dont run it on replit
how to fixx it
it's a replit moment
get a real host
^
hmmm, i will try run code in my pc
yeah that works too
have a variable for the s data, on each dispatch increase its value by 1 and keep sending HEARTBEAT events to the websocket using send_json method
you might want to look into discord.py's gateway code to understand it better
ret = await coro(*args, **kwargs)
File "/home/container/main", line 39, in mines
while tokens > count:
UnboundLocalError: local variable 'tokens' referenced before assignment
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/container/.local/lib/python3.10/site-packages/discord/ext/commands/bot.py", line 1349, in invoke
await ctx.command.invoke(ctx)
File "/home/container/.local/lib/python3.10/site-packages/discord/ext/commands/core.py", line 1023, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
File "/home/container/.local/lib/python3.10/site-packages/discord/ext/commands/core.py", line 238, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: UnboundLocalError: local variable 'tokens' referenced before assignment```
wyvern/gateway/keep_alive.py lines 37 to 45
class KeepAlive:
sequence: int = 0
last_heartbeat: float
async def start(self, ws: "Gateway") -> None:
while True:
await ws.socket.send_json({"op": WSEventEnums.HEARTBEAT, "d": self.sequence})
self.last_heartbeat = time.perf_counter()
await asyncio.sleep(ws._heartbeat_interval)```
`wyvern/gateway/__init__.py` lines 141 to 143
```py
elif op == WSEventEnums.DISPATCH:
self.keep_alive.sequence += 1
await self._dispatch_events(payload)```
the variable isnt defined yet
i mean how can i only use receive once
import discord, os, random
client = discord.client()
KEY = '||sike you thought||'
@client.event
async def on_ready():
print('We logged in as {0.user} '.format(client))
@client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('-hello'):
await message.channel.send('Hello!')
if message.content.startswith('-Hello'):
await message.channel.send('Hello!')
client.run('KEY')
just remove that extra receive
its defined
keep it only in your listen
tells me discord.client doesnt work
and is the dispatch code 0?
yes the OPCODE for dispatch is 0
and tells me to add intents?
sorry, im not dumb enough to not understand what an error says
and python interpreter is not dumb enough to raise a false error
so it is not defined properly
send full code.
damn bro
frfr
uppercase C in Client
and you will need to manually specify intents since v2
a lot of breaking changes between v1.7 and v2
might want to read the migrating guide
anyways i need help😭
but it only run once for on ws connect
i know the c is the problem but everytime i change it to lower or some shit its not working
and it tells me to add intents
wait let me show ya
yeah
read the rest of the message lol
like, i say in the second sentence, that you'll need to pass intents yourself
omg im that dumb
!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.
Since discord.py v2.0.0, it has become mandatory for developers to explicitly define the values of these intents in their code.
oh
can i see your complete gateway file
thanks guys
this is mostly to avoid new users foot-gunning themselves since message content is privileged
let me try it
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.
changes:
- added a _sequence attrs to the class
- updated your HEARTBEAT payload
wait you're correct, you already had it in self.lasts, you were just not increasing the value
but in https://discord.com/developers/docs/topics/gateway#gateway-events-example-gateway-event the sequence number is already included
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
so i dont have to manually increase it?
it is, and you need to tell discord what it was, that you're not doing 🤷♂️
self.lasts,self.op = evente['s'],evente['op']``` and ```json
data = {
"op":1,
"d":self.lasts,
}
```?
is that not what im doing?
hm it should work then , no idea
found it lol
no intents moment, ofc you wont get events
@bot.command()
async def levelr(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 not levelsys[0] == 1:
return
await cursor.execute("SELECT * FROM levelSettings WHERE guild = ? ", (ctx.guild.id,))
roleLevels = await cursor.fetchall()
if not roleLevels:
return await ctx.send("No role levels has been setup!")
em = nextcord.Embed(title="Role Levels", description="Role levels for the server")
for role in roleLevels:
em.add_field(name=f"Level {role[2]}", value=f"{ctx.guild.get_role(role[1]).mention}", inline=False)
await ctx.send(embed=em)```
Ignoring exception in on_command_error
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 629, in setroles
em.add_field(name=f"Level {role[2]}", value=f"{ctx.guild.get_role(role[1]).mention}", inline=False)
AttributeError: 'NoneType' object has no attribute 'mention'```
ill try ty!
im trying to mention a role]
not a user
u can
Ofc you can, just not in the title and field name
oh what
oh not in the name
get_role is cache lookup and it can return None
yeah
tyyy
File "c:\Users\PC\Desktop\Aleccy Bot\main.py", line 629, in levelr
em.add_field(name=f"Role Level", value=f"{ctx.guild.get_role(role[1]).mention}", inline=False)
AttributeError: 'NoneType' object has no attribute 'mention'```
is the cache lookup up to date or it can just be like the role 5 minutes ago?
ru asking me?
asking anyone that knows this
you get the latest aware state of model everytime you use get_x
discord.py updates the cache with each payload they recieve
if you don't get that object it means you haven't subscribed to that intent
ahhhh i forgot about it
things update also receive payload
thats why
ok
help me pls
How do I add the creation date of this post to the footer in discord.py?
how to make the ticket system work after restarting the bot?
Store data in db
So easy to say so hard to do for beginner
https://sqlbolt.com for tutorials
SQLBolt provides a set of interactive lessons and exercises to help you learn SQL
Hey, i've got a question. How can i check when the guild emoji name changes, Looking thru disnake docs on_guild_emojis_update will only get called once a emoji is created/deletedhttps://docs.disnake.dev/en/stable/api.html#disnake.on_guild_emojis_update
can you please send the link?
Not really. the docs saying that so i was just going with the docs
just wanted to be sure
What is the output if you run this command?
It's not a command. It's a event
AuditLogAction is emoji_update
but idk if the event gets fired
1 sec lemme test
it'll be fired even if you modify the name
i see
d.py docs are unclear sometimes
but ig it's specifying create and delete emojis because there isn't an on_guild_emoji_create/delete so the update of an emoji is implied in the name of the event itself
.
Ah it's a tuple so before.name won't work
there are multiple ways:
- Type hint the argument with typing.Literal (example:
typing.Literal["foo", "bar"]) - Use enums and type hint the argument with the enum
- Use @app_commands.choices/discord.app_commands.Choice. (docs: https://discordpy.readthedocs.io/en/stable/interactions/api.html#discord.app_commands.choices)
@app_commands.choices(choices=[
app_commands.Choice(name="Rock", value="rock"),
app_commands.Choice(name="Paper", value="paper"),
app_commands.Choice(name="Scissors", value="scissors"),
])```
My bad, I accidentally deleted my message.
This says TypeError: unknown parameter given: choices
the choices key should match the name of the parameter you want to give the choices to
in your case it should be metal iirc?
@fading marlin py NameError: name 'Choice' is not defined
for this:
@app_commands.command()
@app_commands.describe(fruits='fruits to choose from')
@app_commands.choices(fruits=[
Choice(name='apple', value=1),
Choice(name='banana', value=2),
Choice(name='cherry', value=3),
])
async def fruit(interaction: discord.Interaction, fruits: Choice[int]):
await interaction.response.send_message(f'Your favourite fruit is {fruits.name}.')```
I will try with app_commands rq
you gotta import Choice from app_commands if you just want to use the class
How?
import Choice from discord.app_commands
from discord.app_commands import Choice
This might work as well but i'll do yours
oh yeah it's the same now
this feels violently cursed

python is not typescript 
I wasn't trying to send a poc 😭
I was re-saying what I said earlier
lmao well its 2am and im sleepy so nvm
sleep
for b in before:
for a in after:
if b.name != a.name:
is there a better way to make this code in a one line? to make it look prettier
depends, what are you doing after the if?
Looks like you want to check for something new between 2 lists?
hey robin
Aw that's unfortunate. How you get better ❤️
personally i'm vibing :D
thank you!
glad to hear 😄
I'm just guessing at what you're trying to do as you haven't provided enough information
if that's true, set difference might be of use to you
i actually don't know how to do this lol
Hello, how can we print all the new messages that arrive on the server once the bot is launched?
The on_message event might be of use to you
Okay thanks
does discord have a limit on mongodb database calls
or is it the standard 50 api calls per second ?
limits on accessing your db?
yes, im just trying to calculate how many calls i need to limit per second for scanning my MongoDB
since im using their free 10gb plan per week im calculating how many scans i can realistically do everything for a server 10k members
if that makes sense
discord doesn't limit the amount of times you can access that
that depends on your mongodb host, nothing related to discord api ratelimits
use a caching system if need be
😳 use redis to backup a mongodb server
yea i use aiocache
but thats only if you are accessing the db an insane amount of times
considering mongodb is just BSON, a simple dictionary is more than enough
Hello, I have a big problem. Probably because of intents
Here is my command.
@client.command(pass_context = True, name="test")
async def test(ctx: commands.Context):
for guild in client.guilds:
print(f"nb_members : {len(guild.members)}")
for member in guild.members:
if member.status == discord.Status.online:
status = "online"
elif member.status == discord.Status.idle:
status = "idle"
elif member.status == discord.Status.dnd:
status = "dnd"
elif member.status == discord.Status.offline:
status = "offline"
else:
status = "unknown"
await ctx.channel.send(f"{member.name}#{member.discriminator} is {status} in {guild.name}")
BUT
Client = discord.Client()
Intents = discord.Intents.default()
Intents.members = True
client = commands.Bot(command_prefix = "!", help_command=None, Intents=Intents)
AND
why ..?
you need presence intents enabled in the code
Hey guys
Is there a way to get rid of those exceptions in my console?
discord.ext.commands.errors.CommandNotFound: Command "roll" is not found
Ignoring exception in command None:
That´s basically happening when someone uses a command thats not linked to my bot
use an error handler
Typing kill 1 in replit shell complete bypass it
typing kill 1 changes the ip of replit
And u can also add this in the code to always bypass the rate limit
hmmmm
owo it really works
thank you very much
I would consider
thank you!!!
Makes sense 💀💀
I have folders within the cogs folder, and i want to load that. how would i do that?
You'd prefix the file name with cogs.
Oh wait you have folders within folders
yep
Cogs is the main folder, then i have subfolders like General, Fun, Moderation
i have python files with the subfolders. i want to call them without having all the python files under cogs.
I'd just make a function in the Cogs folder's init.py that adds all the cogs 🤺 and call it whenever i need to load cogs
🫡
import discord
from discord.ext import commands
import random
bot = commands.Bot(command_prefix="!", intents=discord.Intents.default())
@bot.event
async def on_ready():
print('on')
@bot.command()
async def test(ctx):
await ctx.send("Test")``` bot wont respond and no error the bot got admin perm but still
when tried import bot I get this error
from discord import bot
ImportError: cannot import name 'bot' from 'discord' (C:\Users\azim\Desktop\sauceyy\venv\lib\site-packages\discord_init_.py)
help please
This is a different code from the one you showed
there is no library called bot. Have you bot.run(YourToken) in your code, else it won’t work.
You need message content intents
Yes but I think I already did it : ```py
Client = discord.Client()
Intents = discord.Intents.default()
Intents.members = True
client = commands.Bot(command_prefix = "!", help_command=None, Intents=Intents)
"presence" intent 🤺, not "members"
Ok thank you. Such a stupid error like I thinking
What is the best discord api tool for Python?
personally i prefer hikari
discord.py is the most popular one
Read the error?
?
whats wrong with my code
U tried printing it?
The the address1 key came in the ad json ?
How to make the msg we sent from inter "only you can see that"?
use ephemeral kwarg in the method you use to create response, set it to True
Ok
Thanks
.doc
Only for slash command, button, modal
#Using Replit
import discord
import os
my_secret = os.environ['TOKEN']
client = discord.Client()
@client.event
async def on_ready():
print("Logged in as {0.user}".format(client))
@client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith("$status"):
await message.channel.send("Hello!")
client.run(my_secret)
Error:
Traceback (most recent call last):
File "main.py", line 5, in <module>
client = discord.Client()
TypeError: __init__() missing 1 required keyword-only argument: 'intents'
What happened?
!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.
how I made my bot for Only One Channel?
wdym
for example, my bot will only work on the hello 1 channel, it is necessary to try it on the hello 1 channel so that you can use the bot on the hello 2 channel
how?
u need to do that if channel.id != to the id and then send something or return it to the code
😀
Traceback tells you.
can i use the placeholder like this
why doesn't it send the message keyword detected! ```python
def check_message(mess : discord.Message) -> bool:
with open('database.json', 'r+') as f_database:
file_data = json.load(f_database)
keywords = str(file_data["keywords"]).lower()
blackwords = str(file_data["blackwords"]).lower()
if keywords in mess.content.lower(): return True
for embed in mess.embeds:
if embed.title and keywords in embed.title.lower():
return True
if embed.description and keywords in embed.description.lower():
return True
if embed.url and keywords in embed.url.lower():
return True
if any(keywords in field.value.lower() for field in embed.fields if field.value):
return True
return False
@client.event
async def on_message(message):
try:
if check_message(message):
await message.channel.send('keyword detected !')
except:
pass```
?
What
@slvl.command(aliases=['sr'])
@commands.has_permissions(administrator=True)
async def setrole(ctx, level:int, *, role: nextcord.Role):
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 not levelsys[0] == 1:
return
await cursor.execute("SELECT role FROM levelSettings WHERE role = ? AND guild = ?", (role.id, ctx.guild.id,))
roleTF = await cursor.fetchone()
await cursor.execute("SELECT role FROM levelSettings WHERE level = ? AND guild = ?", (levelsys, ctx.guild.id,))
leveleTF = await cursor.fetchone()
if roleTF or leveleTF:
return await ctx.send("A role for that value is already exists! :x: ")
await cursor.execute("INSERT INTO levelSettings VALUES (?, ?, ?, ?)", (True, role.id, level, ctx.guild.id,))
await ctx.send("Updated that level role!")
await bot.db.commit()```
no error when doing the command but also not sending anything in the channel
And JSON isn't a database btw 
wait ill try turning off the command handler
the command isnt found
Does the bot.guilds update in real time?
can someone help me, please
how to send a emoji with id
I want to make a bot that gives a specific role to people that have their twitch connected and displayed on their profile card for my server
can someone point me the right direction for this ?
what is the id of this emoji
I tried using the developer tool and couldn't see its id
ok thank you very much
Bots can't access users' connections. The only way to get them is by using OAuth2
@slvl.command(aliases=['sr'])
@commands.has_permissions(administrator=True)
async def setrole(ctx, level:int, *, role: nextcord.Role):
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 not levelsys[0] == 1:
return
await cursor.execute("SELECT role FROM levelSettings WHERE role = ? AND guild = ?", (role.id, ctx.guild.id,))
roleTF = await cursor.fetchone()
await cursor.execute("SELECT role FROM levelSettings WHERE level = ? AND guild = ?", (levelsys, ctx.guild.id,))
leveleTF = await cursor.fetchone()
if roleTF or leveleTF:
return await ctx.send("A role for that value is already exists! :x: ")
await cursor.execute("INSERT INTO levelSettings VALUES (?, ?, ?, ?)", (True, role.id, level, ctx.guild.id,))
await ctx.send("Updated that level role!")
await bot.db.commit()```
the command isnt found
and i did that for the table
```py
await cursor.execute("CREATE TABLE IF NOT EXISTS levelSettings (levelsys BOOL, role INTEGER, levelreq INTEGER, guild INTEGER)")
like theres no level there so do i add one or???
also thats the slvl group
@bot.group()
async def slvl(ctx):
return
@bot.group(invoke_without_command=True)
async drf slvl(ctx):
return
whys that?
!d discord.ext.commands.Group
class discord.ext.commands.Group(*args, **kwargs)```
A class that implements a grouping protocol for commands to be executed as subcommands.
This class is a subclass of [`Command`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command") and thus all options valid in [`Command`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command") are valid in here as well.
Read the docs
Can u explain him?
still the command isnt working
I am bad at explaining
Try adding pass instead of return
ill try
!traceback
Please provide the full traceback for your exception in order to help us identify your issue.
While the last line of the error message tells us what kind of error you got,
the full traceback will tell us which line, and other critical information to solve your problem.
Please avoid screenshots so we can copy and paste parts of the message.
A full traceback could look like:
Traceback (most recent call last):
File "my_file.py", line 5, in <module>
add_three("6")
File "my_file.py", line 2, in add_three
a = num + 3
~~~~^~~
TypeError: can only concatenate str (not "int") to str
If the traceback is long, use our pastebin.
fixed it and
Cool
nextcord.ext.commands.errors.CommandInvokeError: Command raised an exception: OperationalError: no such column: level
well i know
so do i add one?

???
You send like 5% of the tb.
await cursor.execute("CREATE TABLE IF NOT EXISTS levelSettings (levelsys BOOL, role INTEGER, levelreq INTEGER, guild INTEGER)")
Read it again.
.
py soduim chloride
nice
py salt
Again traceback
send the full traceback
!d discord.ext.commands.Context.voice_client
property voice_client```
A shortcut to [`Guild.voice_client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild.voice_client "discord.Guild.voice_client"), if applicable.
Ok exists
It's a known voice client glitch
You have to write a pretty chunky function for it to detect it.
Hello, I have done this for now but the bot does not send anything, so I tried to reverse it by doing if message.content.lower() in keywords:
then it worked but only when the message contains only the keywords, how can I fix that?
@client.event
async def on_message(message):
with open('database.json', 'r+') as f_database:
file_data = json.load(f_database)
keywords = str(file_data["keywords"]).lower()
blackwords = str(file_data["blackwords"]).lower()
if message.author == client.user:
return
if keywords in message.content.lower():
await message.channel.send('keyword found !')```
yes, what library are you using ?
why doesn't my on_message don't work?
- don't use json files as database
- Reading and writing to files are blocking calls, you should use aiofiles
!pypi aiofiles
send the code
me is like no slash command appear? and then is be die
mh? your Bot die?
no me
pycord also isn't even Discord related 
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Better yet cache in-memory since the file can be serialised in python
it is no prftgryfeq
You can pretty much avoid using aiofiles as well depending on python version, bc asyncio.to_thread
if it exists why you wouldn't use it 😦
Because why should you add an extra dependency when a built-in module exists that does the same thing with less overhead?
meh
gfvhgjg
But again, dependency or not
Just update the cache & write to file whenever the data should be updated
you're switching from client to Bot right?
other way
i think
ping on reply pls
why doesn't the on message not work?
Well you're doing bot.run(...), practically you're not using the client
ok but slash command no appeare
this is the reason
@glad cradle can you help?
you're synchronizing slash commands into the client object that is not runned, so it's not making any API request to create/delete slash commands
yes, lemme read
ohhh
are you getting an error?
btw you're not passing self
wait are you running the client at the end of the file?
i added client.run(token)
client.run("token") ?
below bot.run(token)
yes
yes
bot.run(...) is a blocking call, whatever is underneath will never be executed
same for client.run
idk why it don't work 😦
hold on, I'm testing it
ahhhh it's an intents issue
intents=discord.intents.all() ?
you need to set intents.message_content = True also you're missing self on on_message
btw I'm blind
Hey, is it possible to clone back a deleted a webhook? that was not created by a bot
What does In parameter 'MAXID' name: Command name is invalid mean
Send the entire traceback/error
hii
But it's probably because slash commands' name have to be all lowercase
So on_webhooks_update has just channel as parameter, How can i tell if the before name is not the same as the after name?
!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.
anyone know why i get this when installing easy_pil?
python 3.11?
have you installed Visual studio code build tools?
yes
Can you show your aiohttp version?
For Python v3.11 you should aim for 3.8.3>=
pip show aiohttp
v3.8.3 should've fixed that error since they upgraded Cython
Could you show the full error from the pip install?
Okay, wait I see the error here
So the package easy-pil uses aiohttp>=3.6.0,<=3.8.1 which is in-conflict with your current project
If you have any alternative to easy-pil I'd switch to that, because this project supports v3.10 in the latest from what the meta-data says
any idea why Clyde is responding when I try to use my bots slash cmds? Never seen this before, it's as if I'm blocked by my own bot (?). I tested on my alt account and they work fine there, and prefixed commands work fine
looks like discord canary is broken
what app is this?
currently swapping hosts into a digital ocean vps, using pycord, having some weird import errors with it not finding disc.commands or from discord import Option
any ideas?
just ping on reply ^
can you send a traceback
can you make sure the right discord package flavour is installed, eg pycord rather than
uh what's the other one called
talkin about nextcord? or
your option cog seems to be ... missing??
well the cog thats loading is there, but in line 3/4 i have from discord import Option
upon just removing that seeing if it was just having a tantrum it had an issue with from discord.ext import commands
so is pycord just not installing properly? or am i missing something
wouldn't it be pycord here?
you sure you don't have discord.py installed?
pip show discord
File "C:\Users\beege\PycharmProjects\EconomyDiscordBot\cogs\SpectrumSequence.py", line 122, in __init__
self.add_item(SequenceButton(emoji, emoji_number))
File "C:\Users\beege\PycharmProjects\EconomyDiscordBot\cogs\SpectrumSequence.py", line 126, in __init__
self.emoji = emoji
File "C:\Users\beege\Documents\GitHub\EconomyDiscordBot\bot-env\lib\site-packages\discord\ui\button.py", line 195, in emoji
self._underlying.emoji = PartialEmoji.from_str(value)
AttributeError: 'SequenceButton' object has no attribute '_underlying'
Why?
i dont think
can i downgrade?
How do I get my bot to get the link of an embed
maybe PILLOW?
Uh
?
embeds don't have links, messages do
Links in embeds
what part of embed contains the link?
Example
!d discord.Embed.url if its the title
The URL of the embed. This can be set during initialisation.
@slate swan ^ thats what I meant since the beginning sorry for not being sble to explain correctly
url = yourembed.url
Im not trynna make an embed with a link
Im trying to get the link sent by another bot
…
yes that's it
What u told me is to make an embed with a link
ty
Thats not what im trynna do
i don't see how accessing a property of a object is creating an object
Look
- A bot sends an embed containing a link in a channel
- My bot get that link and store it in a variable
how do you access the name of an user object?
Thats it
thats the shortend form, this is how it will actually work.
message gets sent: on_message event
get embed: message.embeds as a list of embeds sent
getting the url: url = yourembed.url
!d discord.Message.embeds
A list of embeds the message has. If Intents.message_content is not enabled this will always be an empty list unless the bot is mentioned or the message is a direct message.
Embed isn't just the class used to create an embed, its also used returned as a property of a Message
embeds = message.embeds
for embed in embeds:
print(embed.to_dict())
Nothing prints
Which is weird
for embed in embeds:
print(embed.to_dict())```
Indentation may look bad on discord but its correct here btw
do you have message_content intents?
thats weird, mind showing mote code
Ye 1 sec
*more
Can u show me an example of how the on_message event would be? My code is on my pc and im on my phone cause I dong have discors on pc
If possible
@bot.event
async ded on_message(msg: Message):
if not(msg.author.id == id of user to check and msg.embeds): return
for embed in msg.embeds:
# do stuff
*def
Ok let me check
Ded
Yo I fixed it
Cup
But like
Need some help 💀
Yea?
Yes
Check docs
!d discord.Message.embeds
A list of embeds the message has. If Intents.message_content is not enabled this will always be an empty list unless the bot is mentioned or the message is a direct message.
if message.channel.id == "1011881268285280316" or "1011882292253294642":
for emb in message.embeds:
print(embed.title)``` im trynna get my bot to get the titles of the embeds that get sent only in that channel
!or
When checking if something is equal to one thing or another, you might think that this is possible:
# Incorrect...
if favorite_fruit == 'grapefruit' or 'lemon':
print("That's a weird favorite fruit to have.")
While this makes sense in English, it may not behave the way you would expect. In Python, you should have complete instructions on both sides of the logical operator.
So, if you want to check if something is equal to one thing or another, there are two common ways:
# Like this...
if favorite_fruit == 'grapefruit' or favorite_fruit == 'lemon':
print("That's a weird favorite fruit to have.")
# ...or like this.
if favorite_fruit in ('grapefruit', 'lemon'):
print("That's a weird favorite fruit to have.")
Ty
And channel.id return an int btw
I kinda understand the attributes now, but I still don’t understand how I would refer to this
The 490713, the Roblox Protection and the number 4
And get the link specifically get the link above
they are embed fields
Because in embed link is like
[Hello](some link)
!d discord.Embed.fields
property fields```
Returns a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.11)") of `EmbedProxy` denoting the field contents.
See [`add_field()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed.add_field "discord.Embed.add_field") for possible values you can access.
If the attribute has no value then `None` is returned.
Yep^
embed.fields[0]
Got it
And how do I specify which field? There are 3 fields
What i was asking for xd
embed.field[0]?
by index
0 means 1, 1 means 2, 2 meeans 3
Like that
Ye ok ty
embed.fields[0] will pickup 1st field
I thought this is legit embed
!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.
@bot.event
async def on_ready():
print(f"{bot.user.name} is online!")
setattr(bot, "db", await aiosqlite.connect("levels.db"))
async with bot.db.cursor() as cursor:
await cursor.execute("CREATE TABLE IF NOT EXISTS levels (level INTEGER, xp INTEGER, user INTEGER, guild INTEGER)")
await cursor.execute("CREATE TABLE IF NOT EXISTS levelSettings (levelsys BOOL, role INTEGER, levelreq INTEGER, guild INTEGER)")
@bot.group(invoke_without_command=True)
async def slvl(ctx):
return
@slvl.command(aliases=['sr'])
@commands.has_permissions(administrator=True)
async def setrole(ctx, level:int, *, role: nextcord.Role):
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 not levelsys[0] == 1:
return
await cursor.execute("SELECT role FROM levelSettings WHERE role = ? AND guild = ?", (role.id, ctx.guild.id,))
roleTF = await cursor.fetchone()
await cursor.execute("SELECT role FROM levelSettings WHERE level = ? AND guild = ?", (levelsys, ctx.guild.id,))
leveleTF = await cursor.fetchone()
if roleTF or leveleTF:
return await ctx.send("A role for that value is already exists! :x: ")
await cursor.execute("INSERT INTO levelSettings VALUES (?, ?, ?, ?)", (True, role.id, level, ctx.guild.id,))
await bot.db.commit()
await ctx.send("Updated that level role!")
nextcord.ext.commands.errors.CommandInvokeError: Command raised an exception: OperationalError: no such column: level```
Read the error
yeah but even when i try to add it it doesnt work
i added and its the same error
Open database with an app 💀
import discord
from discord.ext import commands
def run_discord_bot():
TOKEN = 'among us'
intents = discord.Intents.default()
intents.message_content = True
client = discord.Client(intents=intents)
@client.event
async def on_ready():
print(f'{client.user} is now keeping people safe')
@client.event
async def on_message(message):
if client.user.id != message.author.id:
if message.author.id == 634260742106775562:
await client.send_message(message.channel, "keep your self safe")
if "word" in message.content:
await client.send_message(message.channel, "response")
@client.command()
@commands.is_owner()
async def shutdown(ctx):
await ctx.bot.logout()
client.run(TOKEN)
bot.run_discord_bot()
File "c:\Users\Legob\Desktop\Discord Bot\nbot\bot.py", line 19, in run_discord_bot
@client.command()
AttributeError: 'Client' object has no attribute 'command'
y broken
Only discord.ext.commands.Bot have .command deco
so thats what i need to import?
And please code like a normal person
whats wrong with it
It will be
@commands.command()
Since u using cogs
from discord.ext import commands
wait so what should i do
Idk
me too
so whats cogs
Look at the example
https://github.com/Rapptz/discord.py/tree/master/examples
is this cogs?
I give up
sorry im super stupid
It is normal command
class example(commands.Cog):
#idk what to do there
@commands.command()
#other thing
It is cog
you didnt even tell me where to look
anyway cogs just organises things into one class, so do i need that at this stage or not
define self.bot in init
someone knows how to add a role if someone has a word in their status? ex hrhrfirhrfi in status
and if they remove the status the bot will remove the role
dont thing discord api allows to see peoples about me
oh ok
thx
like
i have a code that worked for it.. it worked only once (today) and next time it didnt work
but now it just dosent work idk why
It's even more helpful when you want to make your help command, 'cause you can categorize commands under different sections automatically
Hello, I'm working on a script that saves a code in a JSON file. I want the progam to delete that code after 5 minutes, (if It's still in there) How can i do that?
That's why i told #idk what to do here
Which event u were using?
that's why I told you what to do there!
@bot.event()
Oh thanks
1 second
Ok
Status and activity checking is now doesn't support in on_member_update
It totally moved to diff event
async def on_member_update(before, after):
role_id = 1047506245768183888
role = get(before.guild.roles, id=role_id)
if 't5rewsw' in str(before.activities):
if 't5rws' in str(after.activities):
pass
else:
await after.remove_roles(role)
channel = bot.get_channel(1022861332321681418)
embed = discord.Embed(
description=f"Bronze has been removed from {after.mention}",
color=discord.Color.red())
await channel.send(embed=embed)
if 'trer' in str(after.activities):
await after.add_roles(role)
channel = bot.get_channel(1022861332321681418)
embed = discord.Embed(
description=f"{after.mention} has claimed Bronze!",
color=discord.Color.green())
await channel.send(embed=embed)```
oh
async def on_presence_update
And u r done!
thxx
async def on_presence_update(before, after):
Yep
or only async def on_presence_update:
depends on the lib version really
Some of libraries are just forked version of discors.py
Discord*
Some
YOO IT WORKS
tysmmmmm
Nice
I never talked about forks, I was talking about versions...
!d asyncio.sleep 🐈
coroutine asyncio.sleep(delay, result=None)```
Block for *delay* seconds.
If *result* is provided, it is returned to the caller when the coroutine completes.
`sleep()` always suspends the current task, allowing other tasks to run.
Setting the delay to 0 provides an optimized path to allow other tasks to run. This can be used by long-running functions to avoid blocking the event loop for the full duration of the function call.
Example of coroutine displaying the current date every second for 5 seconds:
If it was backdated it should have work in old event
hm
I didn't know what the issue was 💀
Xd
my bad
Np mate
turns out the entire droplet was x) thanks for the catch
What if there are multiple codes? How can i do this to more than 10 codes?
async def delete_after(duration):
asyncio.sleep(300)
with open("file.json","w") as file:
json.dump(newdata,file)
Can i do it thisway?
what is the async for
To await the asyncio.sleep
asyncio.sleep return a coroutine, so, you need to await it
And your entire JSON file can get replace by outdated or old data 🐈
Unless you do the editing in the func
it declares a function to be interpreted as an asynchronous function
get the user using Bot.get_user and the use the send method on the User object returned
bot = ...
user = bot.get_user(user_id)
await user.send(...)
is user_id an int or a string?
Int
oh okay
is anything wrong with my function? ```py
x = 1
user = bot.get_user(418793373365829633)
@bot.command()
async def message(ctx):
await user.send("test")
print("f{x} messages sent")
x + 1
message()
bot.run("token")
TypeError: Command signature requires at least 0 parameter(s)```
Prefix commands must have at least one argument for context object
And you shouldn't call the command in your code like that
Where can I get help
You also need to wait until the bot is ready to use get_user
yeah i don't even want it as a command tbh but i dont know how to do it otherwise
@slate swan
async def on_presence_update(before, after):
role_id = 1047506245768183888
role = get(before.guild.roles, id=role_id)
if 't5rewsw' in str(before.activities):
if 't5rws' in str(after.activities):
pass
else:
await after.remove_roles(role)
channel = bot.get_channel(1022861332321681418)
embed = discord.Embed(
description=f"Bronze has been removed from {after.mention}",
color=discord.Color.red())
await channel.send(embed=embed)
if 'trer' in str(after.activities):
await after.add_roles(role)
channel = bot.get_channel(1022861332321681418)
embed = discord.Embed(
description=f"{after.mention} has claimed Bronze!",
color=discord.Color.green())
await channel.send(embed=embed)```
;-;?
is there a way to make it except in status to be in about me?
Nah
discord api is limited to status and sctivity
Activity not about me
oh ok..
But imma check docs
because if a member is offline
that status will go off
U can block it on the code
If member.staus.idk
Gotta check docs haha
and everytime i am on and off i will get a notification with @rafaaaa.exe has claimed Bronze! Bronze has been removed from @rafaaaa.exe
etc
and its annoying
ikr
i can turn it off tho
Wait
!d discord.Status.offline
The member is offline.
u can make return function where it checks if the member is offline and before.activites == required activities
Then return

Thanks :]
if after.Status.offline and 'required status' in before.activities:
return
Something like dat
@naive briar check if i am wrong 💀
@slate swan
Thanks
How can I throw an exception if there is no member in the list? (Type in @name.error)
where are you getting the list from?
so ```@bot.event
async def on_presence_update(before, after):
role_id = 1047506245768183888
role = get(before.guild.roles, id=role_id)
if 't5rewsw' in str(before.activities):
if 't5rws' in str(after.activities):
pass
if after.Status.offline and 'required status' in before.activities:
return
else:
await after.remove_roles(role)
channel = bot.get_channel(1022861332321681418)
embed = discord.Embed(
description=f"Bronze has been removed from {after.mention}",
color=discord.Color.red())
await channel.send(embed=embed)
if 'trer' in str(after.activities):
await after.add_roles(role)
channel = bot.get_channel(1022861332321681418)
embed = discord.Embed(
description=f"{after.mention} has claimed Bronze!",
color=discord.Color.green())
await channel.send(embed=embed)```
like this @slate swan ? or how
yes, I know how to work with json
How do i assign role in discord.py
are u trying to read custom status'?
yeah
but when the user gets off there is no status and the role will get removed
and im trying to fix
yea so discord is stupid
you need to just add/remove roles when user before status offline
dont send notif
i have a custom cd for mine
to also prevent status changer spam
What's the thing with discord.py rn
can i just use the old version, does it even work or should i move to newest?
i meant 2.0
well it wont from like following month so better shift
guys, how to fix this problem?pls help(I cant post in forum)
guys you know that hidden message?
like this one
only visible to user
ephemeral
Tysm
like this?
yup
has to be a response to a user tho
yep thanks
he is using dpy tho
its not working
can you spot any mistakes?
oh ye
dpy?
yep
yes they are
i hate how they do that
bear with it
psg $
oh u r
maybe forgot some parentheses
but im not that familar with mysql
you should prob ask this in #databases
only possible with interaction
Can anyone send me the offical gist for the slash commands in discord.py? I tried to find it but coldn't.
normal, left and fake not really sure paste where the error says the error is
no official
#discord-bots message
Who has a good tutorial for me to watch and make a ticket bot by myself?
This is what I meant
What
bro 9 months old
TypeError: parameter 'ctx' is missing a type annotation in callback 'say'
eh
when ppl mix up libs...
u are using dpy
yes
dpy ctx dosent have say use send instead also either check docs or best depend on ur ide autocompletes
you don't have ctx annotated in your say function
probably have an extra self that shouldn't be there
i removed the self and the error is
TypeError: parameter 'channell' is missing a type annotation in callback 'say'
now
you need to annotate all arguments in a slash command callback
thats just how discord.py works
i am beginner bro
i would be great if you can explain it in easy words 😭
@client.tree.command(name="say", description="Says")
@commands.has_permissions(administrator= True)
async def say(interaction: discord.Interaction, channell=1, commandd=2):
await interaction.response.send_message(f"arg1 is {channell} and arg2 is {commandd}", ephemeral=True)
Give all of the command's argument a typehint
the code
any1 know some disocrd py stuff i need quick help dm
annotate = typehint
you're following a super outdated tutorial
use message.channel.send("your texr")
bru im trynna make the bot ask a question
the line mentioned in that error is definately not how you do that
can you give some examples
!d discord.Client.wait_for
wait_for(event, /, *, check=None, timeout=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Waits for a WebSocket event to be dispatched.
This could be used to wait for a user to reply to a message, or to react to a message, or to edit a message in a self-contained way.
The `timeout` parameter is passed onto [`asyncio.wait_for()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.wait_for "(in Python v3.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**...
You set a message object as the content
i want it to like say the message i just send
a message is not just the text you send but a complete object storing data related to it
for the text you'll be using msg.content
oh
and it keeps going
someone knows why?
who knows tough to say why without code
i was sending u the code rn sry
async def on_presence_update(before, after):
role_id = 1047506245768183888
role = get(before.guild.roles, id=role_id)
if 'STATUS' in str(before.activities):
if 'STATUS' in str(after.activities):
pass
else:
await after.remove_roles(role)
channel = bot.get_channel(1022861332321681418)
embed = discord.Embed(
description=f"Bronze has been removed from {after.mention}",
color=discord.Color.red())
await channel.send(embed=embed)
if 'STATUS' in str(after.activities):
await after.add_roles(role)
channel = bot.get_channel(1022861332321681418)
embed = discord.Embed(
description=f"{after.mention} has claimed Bronze!",
color=discord.Color.green())
await channel.send(embed=embed)```
@shrewd apex this is the code
how can i get channel id from a channel mentions
like if a user mentions a channel how can i get channel id from that mention?
how do you multiply msg.content? is it msg.content * 2 example?
also thanks
it worked
!d discord.Message.channel_mentions
A list of abc.GuildChannel or Thread that were mentioned. If the message is in a private message then the list is always empty.
any1 able to help
want to multiply whatever the user sends
What are you even trying to do
i say a number, the bot multiplies that number and sends it
message.content return the content of the message in a string, so, you need to convert it to an int
Then multiply it
And you will get an error if the message's content contains an ASCII letter
how
!e
print(int("10293874"))
@naive briar :white_check_mark: Your 3.11 eval job has completed with return code 0.
10293874
It is called basic Python knowledge
check if message.content.isnumeric() , if it is then use int on it
this?
yo guys so i got this
import discord
TOKEN = ""
intents = discord.Intents.default()
intents.message_content = True
client = discord.Client(intents=intents)
@client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
@client.event
async def on_member_join(member):
await bot.send_message(member, "hello")
client.run(TOKEN)```
and it's supposed to send a message when a member joins but it doesnt work
no errors or anything it just doesnt send the message
you need intents.members to be set to True
the code is outdated btw
any1
^
^
where am i supposed to use thta
this?
this new font is so bad
What font 
type f*k you in all caps and looks hot in this font
What the
i never even noticed
replit
well how do i update it
read the docs and don;t use stackoverflow and youtube tutorials
according to this discord.abc.GuildChannel.name should return the name of text channel? eh?
why not
AttributeError: type object 'GuildChannel' has no attribute 'name'
i am getting this error
i tried replacing abc with text channel
TypeError: unsupported type annotation <member 'name' of 'TextChannel' objects>```
? because they are no longer valid

most of them are 2 to 5 years old
can someone help me please? thanks
async def say(interaction: discord.Interaction, channell:discord.TextChannel.name, messagee: str):
you need an instance of the guild class to get its name
i read the docs and my code seems valid
but when i use command in server it says annotation cant be a text channel
problem error said "enter a valid integer" -
ok show me what part of docs has bot.send_message.
discord issue
yes moment loading.
blame javascript for not accepting such long integers

Did you get any errors
channel = cur.execute(f"SELECT * FROM x WHERE xx = :xx ", {"xx": ctx.guild.id}).fetchone()
reroll_channel = await client.fetch_channel(str(channel[2]))
try:
new_msg = await reroll_channel.fetch_message(id)
except:
await ctx.send("The id was entered incorrectly.")
return```
how abt this
await member.send("hello")```
If so, send it
sounds complicated
how? 😭
will work
i tried and it doesnt
is pyhthon not java.
sure
the bot gets online but when i use the command i get an error
async def on_presence_update(before, after):
role_id = 1047506245768183888
role = get(before.guild.roles, id=role_id)
if 'STATUS' in str(before.activities):
if 'STATUS' in str(after.activities):
pass
else:
await after.remove_roles(role)
channel = bot.get_channel(1022861332321681418)
embed = discord.Embed(
description=f"Bronze has been removed from {after.mention}",
color=discord.Color.red())
await channel.send(embed=embed)
if 'STATUS' in str(after.activities):
await after.add_roles(role)
channel = bot.get_channel(1022861332321681418)
embed = discord.Embed(
description=f"{after.mention} has claimed Bronze!",
color=discord.Color.green())
await channel.send(embed=embed)```
nvm, I didn't know you were trying to set a type hint
@fading marlincheck look
can someone help me please? thanks (the message keeps repeating)
how do you make buttons work forever, mine keeps expiring after a few minutes
discord doesn't accept 64 bit (?) integers, you have to type hint a string and then convert it to an int (or use a transformer)
im talking about the server side, not yours.
discord is written in electron js
you need to get an actual channel object
you can't take the id as int, it's a discord limitation
command 'say' raised an exception: TypeError: int() argument must be a string, a bytes-like object or a real number, not 'TextChannel'
Make it persistent
Hmm i see.
ops. xd
take it as str and convert to int on your side
like the #welcome ?
You tried to convert text channel object to int
check views/presistent.py in discord.py repo's example folder
Ah maybe remove str?
discord.TextChannel should work?
mh?
this a slash command right?
import discord
TOKEN = ""
intents = discord.Intents.default()
intents.message_content = True
client = discord.Client(intents=intents)
@client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
@client.event
async def on_member_join(member):
await member.send("hello")
client.run(TOKEN)```
can someone tell me why it doesnt send message on join
yes ig
let me try to fix
sorry but my ba english hehe - but there think remove str?
it didn't populate a option of guild channels?
I meant to type hint id as str id: str
ahh ok check.
you have to enable member intents, which are disabled if you use Intents.default
how do i enable those
!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.
first make sure you have it enabled in the dev portal, then just set intents.members to true
it works thx
IT WORKED
yes tysm
i was converting text channel to int 😭
@glad cradle thanks solution and other error lmao, no problem my check investigate solution later help here ok.
you can send the error if you want
is there any good "base"s for discord bots if that makes sense, ready cog loading system with some small normal commands
(lazy indeed)
Perhaps you would be interested in our "bot-core" repository
We start with this whenever we need a new bot
yo how can i use multiline with .send()
and it keeps going..
someone knows why? btw this is the code
async def on_presence_update(before, after):
role_id = 1047506245768183888
role = get(before.guild.roles, id=role_id)
if 'STATUS' in str(before.activities):
if 'STATUS' in str(after.activities):
pass
else:
await after.remove_roles(role)
channel = bot.get_channel(1022861332321681418)
embed = discord.Embed(
description=f"Bronze has been removed from {after.mention}",
color=discord.Color.red())
await channel.send(embed=embed)
if 'STATUS' in str(after.activities):
await after.add_roles(role)
channel = bot.get_channel(1022861332321681418)
embed = discord.Embed(
description=f"{after.mention} has claimed Bronze!",
color=discord.Color.green())
await channel.send(embed=embed)```
Triple quotes
wym
Or \n for new line
!e
print("""Meow
Meow
Meow""")
@naive briar :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | Meow
002 | Meow
003 | Meow
!e
code
!eval [python_version] <code, ...>
Can also use: e
Run Python code and get the results.
This command supports multiple lines of code, including code wrapped inside a formatted code block. Code can be re-evaluated by editing the original message within 10 seconds and clicking the reaction that subsequently appears.
If multiple codeblocks are in a message, all of them will be joined and evaluated, ignoring the text outside of them.
By default your code is run on Python's 3.11 beta release, to assist with testing. If you run into issues related to this Python version, you can request the bot to use Python 3.10 by specifying the python_version arg and setting it to 3.10.
We've done our best to make this sandboxed, but do let us know if you manage to find an issue with it!
and what if i want an empty line
You would use the new line character
Do you have an link or shall i just bot-core in github lol
!e
print("Hello\nWorld!")
@primal token :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | Hello
002 | World!
i tried and got this
not as simple I would have wanted, but will do thanks
how do you make interaction send a message instead of responding with the message
What library are you using?
just discord.py?
import discord, asyncio
from discord.ext import commands
(intents:=discord.Intents.default()).message_content = True
bot = commands.Bot("!", intents = intents)
bot.command(name="ping")(asyncio.coroutine(lambda ctx: ctx.reply(f"{bot.latency*1000:.2f}")))
bot.command(name="load_ext")(asyncio.coroutine(lambda ctx, ext: bot.load_extension(ext)))
bot.command(name="unload_ext")(asyncio.coroutine(lambda ctx, ext: bot.unload_extension(ext)))
bot.run("...")``` 🤔
simple
you have to respond to the interaction either way
ok
this brings 1 line bot vibes
I'm creating a super simple ticket bot rn 👀
i mean this one is atleast understandable
simple cogs example in discord.py. GitHub Gist: instantly share code, notes, and snippets.
i am shit at bots il pay someone 3$ ltc to help dm less than a line of code
Now use generators since generators => coroutines
dms
✌️
!rule 9
should I call the cops?
ah nvm, you actually wanted already done cogs because you're lazy kek
How can you make a bot with less than a line of code?
; will help me
less than a line
its still a line
you make it in your mind
