#discord-bots
1 messages Β· Page 154 of 1
Is that relevant to anything I'm saying π
oh i js pinged wrong person mb
bro, read the above conversation π
just use a modal
please let me not
good
u can
i have to add a try block
check if '#' on message.content or not
but idk where to add
yes but how do i do that
if not return 
class aclient(discord.Client):
def __init__(self):
super().__init__(intents = discord.Intents.default())
self.synced = False #we use this so the bot doesn't sync commands more than once
this code gives me this error: Traceback (most recent call last): File "/home/runner/modern-economy-bot-4/venv/lib/python3.8/site-packages/discord/client.py", line 409, in _run_event await coro(*args, **kwargs) File "main.py", line 82, in on_ready await self.wait_until_ready() NameError: name 'self' is not defined
add it on check function
def check(message):
return message.author == interaction.user and message.channel == interaction.channel and message.content.isdigit() and client.get_user(int(message.content))
msg = await client.wait_for('message', check=check)```
That certainly is not where the error was raised
thats the code i have when my bot is waiting for a user id @slate swan
def check(message):
if '#' not in message.content:
return
return message.author == interaction.user and message.channel == interaction.channel and message.content.isdigit() and client.get_user(int(message.content))```
ahh waitdidnt edited
what do i add so it also waits for a user to send a message containing #
!e
print("#" in "blah blah balh#")
@naive briar :white_check_mark: Your 3.11 eval job has completed with return code 0.
True
dang example is good π
@slate swan edited btw
He means if "hi" in message.content:
await message.send("hello")
Hey everyone,Β
I made my own bot! It was a cool project, so make sure to read the story: https://medium.com/@rickarentsen/i-made-a-bot-which-can-tell-you-anything-about-computer-science-14da74d57cf5?source=friends_link&sk=bd362e5f691d08c6904c36eb474b4dc6 feedback is appreciated
but i want it to do something if # is sent
await self.wait_until_ready()
if not self.synced: #check if slash commands have been synced
await tree.sync()
self.synced = True
it checks for if # on message.content or not if not it will return
self is simply not defined π€·
means will do nothing
then remove not, "if '#' in message.content():
u r doing it probably outside of the class
in this case ugotta give pass
....
how we gonna know tho π
...........
im bugging
message.channel.send

We won't know unless you show the code
(remember to omit the token)
problem with the await
!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**...
that's literally a check and checks are supposed to just check conditions for passing the message with all the right conditions, you need to do the sending OUT of the check function (which is apparently not an asynchronous function) and after the wait_for
what could it be that im doing wrong
msg = client.wait_for.....
if '#' in msg.content:
.....
ssend the full code
very cruel
so where do i add in this code
def check(message):
return message.author == interaction.user and message.channel == interaction.channel and message.content.isdigit() and client.get_user(int(message.content))
msg = await client.wait_for('message', check=check)```
ikr 
why do you have a get_user in the check oof
because my bot is waiting for a users id
xdremove that line
no
dont need
just use msg.content π
where client is waiting for a message
just get the id within an argument while the command is being invoked
i want my bot to wait for a users id however if the message content has "#" in it i want it to send something else
its not a command
π
Then what is it
@tree.command(name = 'bet', description='Gamble your money. 50% chance of winning with 2x returns!')
async def lotteri_func(interaction: discord.Interaction, amount: int):
db = client.database_connection
cursor = await db.cursor()
USER_ID = interaction.user.id
USER_NAME = str(interaction.user)
user_name1 = str(interaction.user.name)
await cursor.execute("SELECT user_id FROM money_data WHERE user_name = ?", (USER_NAME,))
result_userID = await cursor.fetchone()
if result_userID == None:
await cursor.execute("INSERT INTO money_data(user_name, balance, user_id)values(?,?,?)",(USER_NAME, START_BAL, USER_ID))
await db.commit()
await interaction.response.send_message("Hi, you're a new user and you need to register. \nTo register execute the command one more time!")
else:
await cursor.execute("SELECT balance FROM money_data WHERE user_id = ?", (USER_ID,))
result_userBal = await cursor.fetchone()
amount = int(amount)
Luck = random.randint(1,2)
if isinstance(amount, int) and amount>0:
if amount < int(result_userBal[0]) or amount == int(result_userBal[0]):
if Luck == 1:
new_balance=int(result_userBal[0])+amount
you_won_txt = user_name1+" won "+ str(amount)+ "$"
await cursor.execute("UPDATE money_data SET balance = balance + ? WHERE user_id=?", (amount, USER_ID))
await db.commit()
await interaction.response.send_message(you_won_txt)
else:
new_balance=int(result_userBal[0])-amount
you_lost_txt = user_name1+" lost "+str(amount)+"$"
await cursor.execute("UPDATE money_data SET balance = balance - ? WHERE user_id=?", (amount, USER_ID))
await db.commit()
await interaction.response.send_message(you_lost_txt)
else:
user_not_that_much = user_name1+", you don't have that much money"
how do i add the second thing π
lol
i get this erroe with the code: ```traceback (most recent call last):
File "/home/runner/modern-economy-bot-4/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 289, in lotteri_func
db = client.database_connection
AttributeError: 'aclient' object has no attribute 'database_connection'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/runner/modern-economy-bot-4/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/modern-economy-bot-4/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/modern-economy-bot-4/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 'bet' raised an exception: AttributeError: 'aclient' object has no attribute 'database_connection'
i cant even able to understand, and my brain died, "its not command π "
@slate swan
im using ticket tool in my server when a ticket is made i want the users to send a discord users id and once they send a id my bot checks if the user is in the server and adds them
i want my bot to also check if the message content has "#" in it and if it does to send a different response π
i seeeeeeeeee
There's something called on_message
use modal = BEST
make sense
!d discord.on_message
discord.on_message(message)```
Called when a [`Message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message "discord.Message") is created and sent.
This requires [`Intents.messages`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.messages "discord.Intents.messages") to be enabled.
Warning
Your botβs own messages and private messages are sent through this event. This can lead cases of βrecursionβ depending on how your bot was programmed. If you want the bot to not reply to itself, consider checking the user IDs. Note that [`Bot`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot "discord.ext.commands.Bot") does not have this problem.
but it will always check for every msg tho
i cant have on_message i need it to be wait_for
yah
is there no way to edit wait_for to wait for 2 things
i saw that but i dont understand what in my code was wrong
wait_for's check also check every message that's being sent π€·
You didn't define attribute database_connection for the aclient object
but but
it also makes sense
Reading the error would also told you that
oh i changed my on_ready() function and i believe i messed that up
i will make sure to fix it
cuz u cant check who interacted and whose message to check in on_message
so what do u think guys is it possible
use modal
ez af
cant i just add a
if statement in my function
.....
@commands.has_permissions(administrator=True)
wrong subject
Huh
only bot dev?
!d discord.Guild.owner has got to exist
property owner```
The member that owns the guild.
it changed?
I dunno
!d discord.Guild.owner_id
The guild ownerβs ID. Use Guild.owner instead.
lol
oh exist
xd
if ctx.guild.owner == ctx.author?
works
Id comparison more accurate
yep
That's pretty much the same
MAKES SENSE
xd
@slate swan so dyk how i can do what im tryna do
Do you even know what you're trying to do π§
Biggest question in programming ^
^
Pov middleman bot
No, I don't, but as long as it works... I'm happy 
Sometimes my code works and I donβt even understand why but I donβt complain until someone finds a loophole in the logic of my code
shhhh
Can relate
how do i make my bot wait for 2 things at the same time and send differnet responses based on which is sent first
i currently having it waiting for a users id but i also want it to wait for certain strings
@client.event
async def on_ready(self):
await self.wait_until_ready()
print("Level has been connected to")
setattr(client, "db", await aiosqlite.connect("level.db"))
client.database_connection = await aiosqlite.connect("money_data.db")
await asyncio.sleep(3)
async with client.db.cursor() as cursor:
await cursor.execute("CREATE TABLE IF NOT EXISTS levels (level INTEGER, xp INTEGER, user INTEGER, guild INTEGER)")
await self.wait_until_ready()
if not self.synced: #check if slash commands have been synced
await tree.sync()
self.synced = True
print(f"We have logged in as {self.user}.")
print("Money_data has been connected")
setattr(client, "db", await aiosqlite.connect("level.db"))
client.database_connection = await aiosqlite.connect("money_data.db")
await asyncio.sleep(3)
async with client.db.cursor() as cursor:
await cursor.execute("CREATE TABLE IF NOT EXISTS levels (level INTEGER, xp INTEGER, user INTEGER, guild INTEGER)")
await self.wait_until_ready()
if not self.synced: #check if slash commands have been synced
await tree.sync()
self.synced = True
print(f"We have logged in as {self.user}.")
I get this error: Traceback (most recent call last): File "/home/runner/modern-economy-bot-4/venv/lib/python3.8/site-packages/discord/client.py", line 409, in _run_event await coro(*args, **kwargs) TypeError: on_ready() missing 1 required positional argument: 'self'
Why?
cause it will keep spamming messages when it detects that string buddy
What do you mean
Fr
If you know what you're doing you're learning the wrong coding language
I swear
on_ready doesn't take any argument
Doubt
You should only add self if your function is in a class
If you know what you're doing it's no fun
btw im making dracos bot
Why is this the only channel where we don't have reaction perms
Use on message and detect if the channel is a ticket channel then detect if the message content contains a userID and then check if it contains a #
ur in auto dont u know draco
oh right thank you so much
π
Nop
how did u join auto
Daniel
Try doing this
But honestly I think you should just make an add to ticket command
Because if someone gets pinged in the ticket π
Might detect it as an ID
I'd never understand how that would make sense
I swearbro π
if message.channel.name contains βticketβ π
dont xd
Dies
Lmao
does it really exists? π
Kekekekee
nice
there all confusing tho
make slash command
to add member in ticket
Not me saying this 30 minutes ago
I swear spooky just repeats what I say and its sounds more convincing
π
Create command
Check if the command is being run by the owner of ticket or admin
If yes add user to command
If no output no permission message
I have no clue what the # thing is about gonna need more detail to help
i cant have command
oh its for if users sned other users names
Easy
can somone help me with my verification bot
I want it to listen to the dm for the verfication instead of everything
I have a similar poll system but I want someone help me to make this /poll show
Or something like it at least because I can't think how I may do that
Because followup is a class
await interaction.followup.channel.send(embed=embed)
@slate swan@ember nest, we help with issues here, likely no one will code it for you.
Nah but like I need an example on how it's possible to do
channel could be none getch it first.
I am not asking anyone to code it for me I just need an explanation
What method of verification?
I am using captcha images like number
the user uses the verify command
ok so ive got a working discordbot and in the on_ready function im printing stuff but nothing is printed to console when I use fly.io, if I run it locally everything works fine any ideas?
await interaction.followup.send(embed=embed)
@cloud dawn ( sorry for the ping if it like annoys or anything) can I just show you like the bot ?
cause not sure on how to explain it
Well I only really want to solve coding errors right now.
Maybe someone else can go in depth on it.
alr thats all good thanks
i got 20mins i can take a look if ya want
sure send me dm when you can
Full error?
Check if channel is dms in on message event
its all good I got the help I need thank you tho
after restarting the bot, tickets stop working. How to fix it ?
@bot.command()
async def giveaway(ctx):
def check(m):
return m.author == ctx.author and m.channel == ctx.channel
await ctx.send("What is the giveaway title? e.g `Nitro Giveaway!`")
title = await bot.wait_for('message',check = check, timeout=None)
await ctx.send("Write a giveaway description! e.g `We're having a Nitro Basic giveaway!`")
time = await bot.wait_for('message',check = check, timeout=None)
#other stuff
tome = int(time.content)
channel = await bot.wait_for('message',check = check, timeout=None)
embed= discord.Embed(title=title.content,description=f"**γ» {prize.content} ! ** \ngiveaway : **{timee}**\n*react with {get(ctx.guild.emojis, id = 1050774349512183938)} to enter*\n\n{desc.content}")
await (get(ctx.guild.channels, id= int(channel.content))).send(f"{get(ctx.guild.roles, id = 1045052077258326128).mention}")
message = await (get(ctx.guild.channels, id= int(channel.content))).send(embed=embed)
await message.add_reaction(f"{get(ctx.guild.emojis, id = 1050774349512183938)}")
await sleep(int(time.content))
await message.edit(content="giveaway ended!")
if message.reactions:
users= await message.reactions[0].users().flatten()
if users:
users.remove(bot.user)
winner=random.choice(users)
await (get(ctx.guild.channels, id= int(channel.content))).send(f"Congrats, {winner.mention}, you won **{prize.content}** ! dm a staff within 48 hours to redeem your gift.")
else:
await (get(ctx.guild.channels, id= int(channel.content))).send('There are no users in this giveaway!')
else:
await (get(ctx.guild.channels, id= int(channel.content))).send('there are no reactions in this giveaway!')
even though there are reactions on the message, it says there are no reactions as in the else conditional, why?
Hello people (again)
I'm trying to using slash commands, but the command don't appear in slash list
i looked on docs, gits.github of umbra, youtube videos, stack overflow, but nothing worked
My code is right apparently
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
uhum
the ping.py is a cogs
how would I make a make a command that changes all channel perms? Like Im trying to make a command that makes it where every single channel disables threads
class Welcome(commands.Cog, name='Welcome'):
'''setwelcome'''
def __init__(self, bot):
self.bot = bot
self.responses = ['']
@commands.Cog.listener()
async def on_ready(self):
print('am ready, gonna try to create welcome db')
self.bot.db = await aiosqlite.connect('welcome.db')
print('welcome db has been connected to! time to create the welcome table')
async with self.bot.db.cursor() as cursor:
await cursor.execute("CREATE TABLE IF NOT EXISTS welcome (guild INTEGER, welcomeChannel INTEGER)")
print('welcome table created!')
await self.bot.db.commit()
print('db has been committed!')
hi, im trying to create a database for my Welcome Cog. however, the above code does not seem to be creating any file at all. None of the print statements show up in the console. Could anyone help me figure out why the on_ready() is not firing?
How do I create a dashboard?
I've created a few. Do you have a specific question or are you looking for more of an overview or "where do I get started" type question?
Using reactions or button?
Can you show us the code for where the cog is being loaded?
Add some prints to debug your code
overview
bot.add_cog it's a coroutine so use a setup async function to add your cog.
async def setup (bot):
await bot.add_cog(Welcome)
I create a huge dashboard in discord channel for my bot
Sure.
My frontend was created with
- my favourite stack for any framework.
I use
as my Typescript ORM to interface with my backend database - 
For the actual bot, I'll use
(90% of the time) or discord.js or serenity.rs 
Speaking truth?
Yeah
Oh and you'll want a REST API with
or
or 
Rocket + Diesel is the Rust alternative if you want that
How are you going to create?
The idea is to seperate your bot, frontend, and API
Its not easy but if you can't build a website (no full stack knowledge) build it in discord
The API should be the "source of truth". The bot and frontend will communicate to the API
This is the step that people usually have a lot of trouble with
They think that they need to somehow directly connect their bot and their frontend - so they go for something like Quart which is not at all what you want
oh
It is quite a fun project to go with! I learned a bunch of different tools that way
I made a channel called "Dashboard"
I'm that channel bot send a message with a selection menu (like I websites Navigation bar),in that message I add all of my bot modules etc), like Music, Moderation, Administration etc.
If you press one of theses options bot will create a channels called (option-tab)
Like (#music-tab or #moderation-tab etc).
I'm Brazilian and I don't understand much English, I'm translating.
In that new channel bot sends another message with all options like:
Music
play command β
stop commandβ
And all of my Music Functions (if is on β
else β)
Below this message I have some buttons like (go back,edit,save)
Pick a stack of tools you want to work with.
I don't want to create a music bot I want to create a website where people can configure the bot.
That was a small preview of my dashboard,but as I said its not easy.
Yes. So pick a web framework, the API framework, CSS frameworks, all of that
Not as difficult as it may seem
Music it's one of my bot functions (a example).
To make you understand how the dashboard works
Its like a mee6 dashboard but in discord.
I need assistance.
1 You define your bot 2 times,as a client and as a bot
2 you never define the intents
what code specifically do I replace and with what?
π«€π
I'm not familiar with python, is it just a simple code change or what
@bright wedge I just cant seem to figure out where client is defined twice and how to define the intents
:<
:incoming_envelope: :ok_hand: applied mute to @slow zodiac until <t:1670892265:f> (10 minutes) (reason: discord_emojis rule: sent 41 emojis in 10s).
The <@&831776746206265384> have been alerted for review.
!unmute 795672438708240448
:incoming_envelope: :ok_hand: pardoned infraction mute for @slow zodiac.
Hi
Hi, I was wondering if I can please get some assistance on SQLite3, thank you!
Are you really going to create one for me?????
Dm me
I didn't understand?
Direct message
Will you help me create the dashboard? I wanted to know how you will help me.
You need to do math πΏ
That's called Progress Bar, you can find a lot of libraries doing that!
Or create your own but yes as Spooky said you need math knowledge.
Yep that's wayy more easy
Some library supports that with ascii characters
interaction.followup.send
π€·
Idk if try
Ig
@bot.event
async def on_ready():
bot.db = await aiosqlite.connect("level.db")
bot.db = await aiosqlite.connect("bank.db")
bot.db = await aiosqlite.connect("blocked.db")
db=sqlite3.connect('main.sqlite')
cursor=db.cursor()
cursor.execute('''CREATE TABLE IF NOT EXISTS main(guild_id TEXT,msg TEXT,channel_id TEXT)''')
print('We have logged in as {0.user}'.format(bot))
initial_extensions = ['cogs.leveling','cogs.moderation', 'cogs.welcome', 'cogs.react', 'cogs.background','cogs.economy', 'cogs.log', 'cogs.giveaway','cogs.ticket']
await bot.wait_until_ready()
if __name__ == '__main__':
for extension in initial_extensions:
try:
bot.load_extension(extension)
except commands.errors.ExtensionAlreadyLoaded:
pass
except Exception:
print(f'Failed to load extension {extension}', file=sys.stderr)
traceback.print_exc()
Ah that's why
Your cog is loaded after the bot is ready
ye i have that at the end of my cog
So the on_ready inside the cog is never going to run
You should also not be doing this much stuff in on_ready
An on ready should at most contain a print statement
Anything more than that is a no no
i see, would adding something liike await asyncio.sleep(3) inside the on_ready in welcome cog help?
also thank you, i will see if i can shorten the things in my on_ready code in main
Nope
@austere vale move all of the stuff you have in on_ready into setup_hook, it'll fix both problems
can you show me an example of how to use setup_hook?
Sure.
class MyBot(commands.Bot):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
async def setup_hook(self):
# Perform database connections here
# Perform .load_extension here
# Perform any other tasks that need to be done on startup
bot = MyBot(command_prefix="!", intents=discord.Intents.default())
@bot.command()
async def my_command(ctx, ...):
...
bot.run(...)
you can use ```py
bot = commands.Bot(...)
@bot.event
async def setup_hook():
...
what would the difference between having subclass and not having subclass be? since this would go into main.py
A subclass gives you a lot more flexibility in the future, but can be a bit more difficult to set up.
Without a subclass, easier to set up but can be a pain if you need to do some specialized things.
Generally I will always subclass at the start when it's not that hard to, and it gives me a lot more wiggle room
bot = commands.Bot(command_prefix='~',case_insensitive=True,
intents=nextcord.Intents.all())
bot.remove_command('help')
@bot.event
async def setup_hook():
bot.db = await aiosqlite.connect("level.db")
bot.db = await aiosqlite.connect("bank.db")
bot.db = await aiosqlite.connect("blocked.db")
db=sqlite3.connect('main.sqlite')
cursor=db.cursor()
cursor.execute('''CREATE TABLE IF NOT EXISTS main(guild_id TEXT,msg TEXT,channel_id TEXT)''')
print('We have logged in as {0.user}'.format(bot))
initial_extensions = ['cogs.leveling','cogs.moderation', 'cogs.welcome', 'cogs.react', 'cogs.background','cogs.economy', 'cogs.log', 'cogs.giveaway','cogs.ticket']
await bot.wait_until_ready()
if __name__ == '__main__':
for extension in initial_extensions:
try:
bot.load_extension(extension)
except commands.errors.ExtensionAlreadyLoaded:
pass
except Exception:
print(f'Failed to load extension {extension}', file=sys.stderr)
traceback.print_exc()
i moved everything under the setup_hook but it doesnt seem to be running, did i do something wrong?
you shouldnt have bot.wait_until_ready inside a setup hook
!d discord.Client.setup_hook
await setup_hook()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
A coroutine to be called to setup the bot, by default this is blank.
To perform asynchronous setup after the bot is logged in but before it has connected to the Websocket, overwrite this coroutine.
This is only called once, in [`login()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.login "discord.Client.login"), and will be called before any events are dispatched, making it a better solution than doing such setup in the [`on_ready()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_ready "discord.on_ready") event.
Warning
Since this is called *before* the websocket connection is made therefore anything that waits for the websocket will deadlock, this includes things like [`wait_for()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.wait_for "discord.Client.wait_for") and [`wait_until_ready()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.wait_until_ready "discord.Client.wait_until_ready")...
read the last warning
you can use awaits, just not gateway things
do you think there could be anything else in the function thats causing it not to run? i moved it to be right before my bot.run(token)
but the cogs still appear to not be loading
if name == 'main': cause of this
actually that shouldnt matter hm
await bot.wait_until_ready()
did you remove this?
yes i removed it
the print('We have logged in as {0.user}'.format(bot)) is not printing so maybe something before that is making it go wrong?
@bot.event
async def setup_hook():
bot.db = await aiosqlite.connect("level.db")
bot.db = await aiosqlite.connect("bank.db")
db=sqlite3.connect('main.sqlite')
cursor=db.cursor()
cursor.execute('''CREATE TABLE IF NOT EXISTS main(guild_id TEXT,msg TEXT,channel_id TEXT)''')
print('We have logged in as {0.user}'.format(bot))
initial_extensions = ['cogs.leveling','cogs.moderation', 'cogs.welcome', 'cogs.react', 'cogs.background','cogs.economy', 'cogs.log', 'cogs.giveaway','cogs.ticket']
if __name__ == '__main__':
for extension in initial_extensions:
try:
bot.load_extension(extension)
except commands.errors.ExtensionAlreadyLoaded:
pass
except Exception:
print(f'Failed to load extension {extension}', file=sys.stderr)
traceback.print_exc()
await bot.change_presence(activity = nextcord.Activity(type=3, name=' for ~help | DM me or use ~setup_ticket to send the mods a message!'))
await bot.load_extension
do i need a login() somewhere?
no
i see, i'll try to change my code w ur feedback and make it work
thank u for helping!
what are the pros/cons to using nextcord, pycord or discord.py?
Pycord generally has a bad rep. Toxic community.
Nextcord has a similar deal - not the community but more or less lack of support.
As it stands discord.py is probably the best if not one of the best libraries to be using simply because it's the oldest, has the largest community support, and the most stable codebase
alr thanks!
Hi Robin
not essentially toxic, but the consistent argument from their community ( community, not the developers ) that it's far better than any other existing libraries which includes discord.py and other forks is just way too annoying. in contrast the codebase is not too appealing and pycord has some bad abstractions when compared to other libs
In terms of community discord.py isn't much better either...
Just look at their server, lol. It's common knowledge that it's not the best
agreed, definitely not beginner friendly π
lol tbh they shit on other libraries more than forks do
heh, The main difference I see on d.py community is a lack of patience for those that don't put in effort and just want the answers
I'm not on the others though
We don't have that much patience for that here either
But we go about it in a nicer way rather than just
"You suck at coding never try to code again"
heh. I don't see that much over there either. An occasional dog pile. Just more blunt like "learn python" or "this is basic python"
the famous ?tag lp
onto a question I have though. There really is no way to gauge a member's last activity in a guild without message_content and storing stuff in a db is there?
Gauge how, exactly?
timestamp vs joined_at
message_content is required only for the text part of message, you still get the message objects
oh ok, so I can still get on_message events?
ofcourse!
I thought those got silenced for some reason
the message.content will just be None, thats all
alright, so essentially on each event do an upsert in a small db with the timestamp?
yeah that should work
Am I right in thinking there is no built-in way?
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...
yeah probably not ideal
this iterates through the channel history, so you can find the user's last message
but that will be a heavy task
granted pinging my sqlite db on each message isn't ideal either
heh... but probably more ideal than getting ratelimited
you could use a cache and a task that updates the sqlite db after some time ```py
user_dict: dict[int, int] = {}
async def on_message(msg: Message) -> None:
user_dict[msg.author.id] = int(msg.created_at.timestamp())
@tasks.loop(your time)
async def update_db_task():
clone = user_dict.copy()
user_dict = {} # reset the dictionary
# insert the values from the clone dictionary` now
i did it in one of my bots
yeah but if the bot crashes you do lose accuracy
you do lose accuracy when the bot crashes anyhow lol
Hah fair point.
How to get contributors for bot π©
What kind
allow bad commits ππΏ
get some ppl like me π
hi guys. is there anyone using crawling/scraping bot for 24h on AWS EC2?
Literally nobody commits, that wouldn't help lmao
emotional damage
sarth, any good ways to learn db
sqlite
idk maybe suggest which is better
well all you can do is wait for the project to get bigger lol, people usually tend to commit on them for contributor roles or something in support servers
sqlbolt to learn sql
whats that
SQLBolt provides a set of interactive lessons and exercises to help you learn SQL
any yt tutorial? 
altho docs always better ngl
SQL is relatively easy so SQLBolt might be better than a video
Airdata returns None even if I do something like .weather realtime New York -i, anyone have any ideas why?```py
@weather.command(name = "realtime", aliases = ("now", "standard", "current"))
async def realtime(self, ctx: commands.Context, *, city: str, airdata: Union[Literal["-i"], None] = None):
the complete string is being consumed by your "city" variable
cant able to do the first task π
you can remove the * from there and invoke the command like this
sarth help ;-;
!weather realtime "New your" -i
did you read everything there lol?
i read π
still what to do no idea
GOT IT
YESSIR
wondering if someone is able to point me in the right direction to fix and issue I'm having, im using "async def clear(ctx, amount=1):" which is expecting an int as an input which is causing it to crash on anything else. I'm trying to work out how I can validate that the inputted is an int and if not throw out a message
uhjhjjjjjjjj im going to die
hahaha
amount: int
when i run it on my computer, it's working as well , but why does the bot not respond when i run it on AWS EC2?
if amount not int:
...
other commands are working but only scraping command is not working. even not stop the bot with error
code pls
maybe bcuz of ip
thanks Spooky, ill give this a go π
@bot.command()
async def site_name(ctx):
old_links = []
while True:
try:
channel = bot.get_channel(PUT CHANNEL CODE WHERE YOU WANT TO RECEIVE)
base_url = 'scraping URL'
async with aiohttp.ClientSession() as sess:
async with sess.get(base_url, headers={'user-agent': 'Your user-agent'}) as res:
text = await res.text()
soup = bs(text, 'lxml')
title = soup.find("", attrs={})
link = soup.find("", attrs={})
if link not in old_links:
embed=discord.Embed(title=title, url=link)
embed.set_author(name="Site name")
await channel.send(embed=embed)
old_links.append(link)
else:
pass
except Exception as e:
await channel.send("β Site name = Error Please Check β")
await asyncio.sleep(180)
if __name__ == '__main__':
bot.run(TOKEN)
yeah so i tried to printed with print() on jupyter that connected with AWS EC2 but it's working
hmmmmmm any error?
that command is not working on AWS EC2.. so i am trying to find a reason all day haha
yeah exactly
computer is computer even it is rdp or not
just not respond. bot keep working without any error messages on discord and error code in terminal
that is not our main thing to think xd
on_ready works?
yes
and it's working. but when i tried to start this, nothing respond
i c
even this simple command too.. when i write "ping" respond "pong!" well
can i check the on_message?
@bot.event
async def on_message(message):
if "=chart" in message.content:
await asyncio.sleep(2)
await message.delete()
await bot.process_commands(message)
return
elif message.content == "ping":
await message.channel.send("pong!")
await bot.process_commands(message)
return
Only this
ur process commands is inside in if statement
make it out side or use |
@bot.listen()
oh
@bot.event
async def on_message(message):
await bot.process_commands(message)
if "=chart" in message.content:
await asyncio.sleep(2)
await message.delete()
return
elif message.content == "ping":
await message.channel.send("pong!")
return```
also if u have multiple events use @bot.listen()
also why u returning at last
remove return
ohhhhhhh... wow
but why is this not respond anything?.. this is the main reason why i trying to making a bot
because of not processing on_message event
thank you so much for your help sir
wait ur intents enabled?
may i ask you where can i find this information? like docs
ohhh thank you so much
is this the problem what makes not respond scraping command?. just fixed with this code and working scraping command too.
ofc
u need to process commands
or use @bot.listen()
so bot can listen for prefix commands too
Learning a lot from you . Thank you very much
What's the best way to make flag arguments to a discord bot?
use app commands, makes life easier
!d discord.ext.commands.Flag or this
class discord.ext.commands.Flag```
Represents a flag parameter for [`FlagConverter`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.FlagConverter "discord.ext.commands.FlagConverter").
The [`flag()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.flag "discord.ext.commands.flag") function helps create these flag objects, but it is not necessary to do so. These cannot be constructed manually.
whats that
this is like poor version of app commands 
yes.
Oh thanks, never notice that.
it was added recently ( in 2.0 )
Is the like .help command --h? --h being the flag?
type of flags can be customised its usually like ```
.help command h: value_for_h_argument
you can chexk the docs for customisation
Ah, would having something like --h be possible with commands.Flag?
yes
But this wouldn't be possible I assume?```py
async def foo(self, ctx, *, text, flag_stuff):
big brain stuffs going on
no
you can't have 2 args after *
if u put
then what ever u type for text
i mean u cant reach the flag stuff
What about this?```py
async def foo(self, ctx, flag_stuff, *, text):
idk i am not even better at explanation

What would happen if I didn't include the flag?
?
.search Python Discord
.search --a Python Discord
Would both work with:```py
async def foo(self, ctx, flag_stuff, *, text):
--a = flag_stuff
Python Discord=Text
Yeah
it will count ad like dat
as*
But in the first one, would Python count as the flag?
no
only --a
Is it because of the prefix?
no
--
1st one will work like dat:
Python = flag_stuff
Discord=text
2nd one i told already
You said the opposite above..
if u really want to add --a use subcommand
ig
yea 
this is ur 2nd example
What I need is something like:```
!search [<--a> (optional, must say --a to count as the first arg)] <text>
cool
what about subcommand
Never tried it.
Are there any good examples online?
@bot.group()
async def search(ctx):
pass
@search.command(name="--a")
async def a(ctx,text):
...
here is a simple example
then .search --a u gotta must do
Ah, I'm already using that, can you have a subcommand of a subcommand?
and --a's argument is text
ig cogs better
i can drop u a example from github tho
Sure
1 min
This is how my command actually is supposed to be:```
!weather <realtime (subcommand)> [--a] <text>
With prompt: Can you write a basic Discord bot that has one command that sends hello world in python
The code doesnt work and isnt very good but holy did it ever come close
any error?
also there is no intents enabled
hold on
As far from the intents this should work.
@bot.event
async def on_message(message):
await bot.process_commands(message)
if message.content == "ping":
await message.channel.send("pong!")
await asyncio.sleep(2)
await message.delete()
return
May i know how to delete "pong!" message sent from bot in this code?
Delete_after kwarg
is this ur code?
like full code?
The ai generated it for me using that prompt
ChatAI is really cool.
intents is the problem for sure
well cant able to find the example ah
Hi, my bot printed this, what is it about and how can i fix it if it needs fixing
code
how to use the permission "Join server for you" in discordpy?
u need to close the session btw
π its in developer portal scopes
guilds.join
scope
can you send me the sample code?
i didnt really used this code so i cant sorry
;-; ok
how?
and when do we need to close it?
also, do i send the code here? its got some sensitive information such as passwords
censore the password tokens and other things and give it here
censor*
!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.
ok
so basically this bot im using to fetch posts from reddit and send to discord
ic
is this ur whole code?
yeah
hmm
its running on railway and works fine, but it printed those messages so i was wondering if i should be concerned
ok so
this class returns the Interaction of a user as an event?
inside event i will check if the interaction is from the select menu i want
then it will tell what the user selected like? eh
isnt it same to view?
The warning is not releasing resources. Aiohttp does http fetched. Probably your Reddit library. Make sure you do any necessary cleanup or use their recommended context managers.
except that you don't need to add it manually for all select roles
also i have to use slash command to create the menu?
not necessarily if you're able to take inputs with a prefix command that shouldn't be a problem
How do I transfer the written stuff in txt file to embed in a discord bot?
guys I need help
it shows me "discord.ext.commands.errors.CommandInvokeError: Command raised an exception: UnboundLocalError: local variable 'tower1' referenced before assignment" this error.
!e ```py
if 1==3:
monkeys = "otters"
print(monkeys)
lemme send the code
sure
!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.
wdym
OH RIGHT
I accidently wrote that π
it shows this error now
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: set_footer() missing 1 required positional argument: 'self'@slate swan
you were supposed to use that with an embed instance, not a embed type
so how do I fix it?
I rlly havent coded in a long time
em=discord.Embed(title="", description="")
wait I got my mistake
Can someone help me it says atributeerror: module 'discord' has no atribute 'bot'
good boy
!d discord.ext.commands.Bot
class discord.ext.commands.Bot(command_prefix, *, help_command=<default-help-command>, tree_cls=<class 'discord.app_commands.tree.CommandTree'>, description=None, intents, **options)```
Represents a Discord bot.
This class is a subclass of [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client") and as a result anything that you can do with a [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client") you can do with this bot.
This class also subclasses [`GroupMixin`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.GroupMixin "discord.ext.commands.GroupMixin") to provide the functionality to manage commands.
Unlike [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client"), this class does not require manually setting a [`CommandTree`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandTree "discord.app_commands.CommandTree") and is automatically set upon instantiating the class.
async with x Asynchronously initialises the bot and automatically cleans up.
New in version 2.0.
it shows this like
what do i do with that im new
shopw ur code
Hey @slate swan!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
do \n instead of /n
Hey @slate swan!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
ohhh
Hey @slate swan!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
ok
you got it mate
help plsss
ohh
wait the command isnt working
name=str(message.author.id)
await create_category(name, *, overwrites=..., reason=None, position=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Same as [`create_text_channel()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild.create_text_channel "discord.Guild.create_text_channel") except makes a [`CategoryChannel`](https://discordpy.readthedocs.io/en/latest/api.html#discord.CategoryChannel "discord.CategoryChannel") instead.
Note
The `category` parameter is not supported in this function since categories cannot have categories.
Changed in version 2.0: This function will now raise [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "(in Python v3.11)") instead of `InvalidArgument`.
need to give position
ah
what about them tho
!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.
catg=guild.channels
category is a type of channel object
utils.get(guild.channels,..)
Run black on this
yes
commands still not working
Hihi, I was wondering if using an ORM such as SQLAlchemy would be required instead of just running a driver to link to a database to store data from the bot? sorry if this is worded badly >.<
channel=utils.get(cteg.channels, name=....)
from where u r getting this codes xd
@slate swan HELP PLEASEEE command no work
show ur new code
bro
u r creating likewtf
what is again topic
Hey @slate swan!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
??
channel = await categ.create_text_channel(name=f"{message.author}", topic = str(message.author.id))
wth is this
name = message.author.id
ye
again what is topic? channel desc?
@slate swan
checking
bro what are u trying to do i cant understand bruh
ok
ok cool
channel = utils.get(categ.channels, str(message.author.id))
....
name=str(...)
......
bruh
π im soooooooooo confused
wdym
showing
@slate swan wdym u dont understand
name=str(message.author.id)
remove this line
@slate swan
remove it?
yes
including the "bfroulette"
?
add back aagain
did u enable intents on developer portal?
yes
then bro really idk
when i type the command it dosent work for some reason
ur bot should work
@vale wing help him i give up π
it says command roulette not found
@slate swan what is your issue
idk command just isnt working
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
Hey @slate swan!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
latest30 = (
games["history"][0]["winningColor"] + " " +
games["history"][1]["winningColor"] + " " +
games["history"][2]["winningColor"] + " " +
games["history"][3]["winningColor"] + " " +
games["history"][4]["winningColor"] + " " +
games["history"][5]["winningColor"] + " " +
games["history"][6]["winningColor"] + " " +
games["history"][7]["winningColor"] + " " +
games["history"][8]["winningColor"] + " " +
games["history"][9]["winningColor"] + " " +
games["history"][10]["winningColor"] + " " +
games["history"][11]["winningColor"] + " " +
games["history"][12]["winningColor"] + " " +
games["history"][13]["winningColor"] + " " +
games["history"][14]["winningColor"] + " " +
games["history"][15]["winningColor"] + " " +
games["history"][16]["winningColor"] + " " +
games["history"][17]["winningColor"] + " " +
games["history"][18]["winningColor"] + " " +
games["history"][19]["winningColor"] + " " +
games["history"][20]["winningColor"] + " " +
games["history"][21]["winningColor"] + " " +
games["history"][22]["winningColor"] + " " +
games["history"][23]["winningColor"] + " " +
games["history"][24]["winningColor"] + " " +
games["history"][25]["winningColor"] + " " +
games["history"][26]["winningColor"] + " " +
games["history"][27]["winningColor"] + " " +
games["history"][28]["winningColor"] + " " +
games["history"][29]["winningColor"] + " " +
games["history"][30]["winningColor"] + " "
)```
That can be shortened to py latest30 = " ".join(games["history"][i]["winningColor"] for i in range(30))
uh
LOL
no
That's required
Whatever the opposite of DRY is this is it
Ikr
if lastgame1 == "red":
lastgame1 = "π₯"
if lastgame1 == "purple":
lastgame1 = "πͺ"
if lastgame1 == "yellow":
lastgame1 = "π¨"```
To this
```py
d = {
"red": "π₯",
"purple": "πͺ",
"yellow": "π¨"
}
lastgame = d[lastgame]```
if prediction == "π¨":
accuracy = "85%"
elif prediction == "π₯" and latest30numred <= 3:
accuracy = "81%"
elif prediction == "π₯" and latest30numred <= 6 and latest30numred >= 4:
accuracy = "77%"
elif prediction == "π₯" and latest30numred <= 9 and latest30numred >= 7:
accuracy = "72%"
elif prediction == "π₯" and latest30numred <= 12 and latest30numred >= 10:
accuracy = "68%"
elif prediction == "π₯" and latest30numred <= 12 and latest30numred >= 10:
accuracy = "62%"
elif prediction == "π₯" and latest30numred <= 15 and latest30numred >= 13:
accuracy = "55%"
elif prediction == "πͺ" and latest30numpurple <= 3:
accuracy = "81%"
elif prediction == "πͺ" and latest30numpurple <= 6 and latest30numpurple >= 4:
accuracy = "77%"
elif prediction == "πͺ" and latest30numpurple <= 9 and latest30numpurple >= 7:
accuracy = "72%"
elif prediction == "πͺ" and latest30numpurple <= 12 and latest30numpurple >= 10:
accuracy = "68%"
elif prediction == "πͺ" and latest30numpurple <= 12 and latest30numpurple >= 10:
accuracy = "62%"
elif prediction == "πͺ" and latest30numpurple <= 15 and latest30numpurple >= 13:
accuracy = "55%"
else:
accuracy = "Error" # yes the accuracy is hard coded what are you gonna do about it```
The what
latest30red = "red"
latest30numred = latest30.count(latest30red)
latest30purple = "purple"
latest30numpurple = latest30.count(latest30purple)
latest30yellow = "yellow"
latest30numyellow = latest30.count(latest30yellow)```
At this point better to make latest30 a list
Hi
Please where can I find an API that gives updates on new altcoins that are launched
ok
so i what do i do with this
For a discord bot
i gave up for that mess xd
LOL
search in google u will eventually find
Been on that for the past hour
Anyway what's this
def roulette(ctx):
BFRoulette = scraper.get("https://rest-bf.blox.land/games/roulette").json()["history"]
yield [
BFRoulette[0]["winningColor"],
[(winningColor["winningColor"])
for winningColor in BFRoulette[-2:]]
]```
Or any site that I can scrape
Useless yield
it says indentation error now lol
Indentation errors are easily solvable
dont tell me scraper here is import requests as scraper
Thx god it's not
there ain't as much fluids on earth to support opposite of that π
@worldly portal this seems like easy to scrap and they probably have API https://coinmarketcap.com/new/
I am not gonna fix indentation error
I tried asking an AI for optional flags in discord commands. It gave me this, but as far as I know this isn't a thing, is it?
@commands.command()
@commands.option('--flag', '-f', required=False)
async def my_command(self, ctx, *, text: str, flag: str = None):
if flag:
# do something if the flag is present
else:
# do something if the flag is not present
To my knowledge flags are done differently
I made this to make sure that the command doesn't work for users who have no permission.
and it's working
from discord.ext.commands import Bot, has_permissions, MissingPermissions
@bot.command()
@has_permissions(administrator=True)
async def dog(ctx):
i = randint(1, 30997)
url = f'https://loremflickr.com/320/240/dog?lock={i}'
embed=discord.Embed()
embed.set_image(url=url)
await ctx.message.channel.send(embed=embed, delete_after=10)
But if person who have no permission uses the command, an error code is displayed on the terminal. is this right??
in predicate
raise MissingPermissions(missing)
discord.ext.commands.errors.MissingPermissions: You are missing Administrator permission(s) to run this command.
Yeah this is right, you can handle the errors with on_command_error event
Ohhhhh thank you!!!
can someone help w making that value in embed
like trying to do that but idk how
em.add_field(name="Link", value="Click Me!")```
oh thanksss
How can i check if a message is older then 2 Weeks?
if (discord.utils.utcnow() - message.created_at).days >= 14```
TThx
if isinstance(message.channel, discord.DMChannel):
guild = bot.get_guild(1032284161421099108)
categ = utils.get(guild.channels, name = "ModMail Tickets")
if not categ:
overwrites = {
guild.default_role : discord.PermissionOverwrite(read_messages = False),
guild.me : discord.PermissionOverwrite(read_messages =True)
}
categ = await guild.create_category(name ="ModMail Tickets", overwrites=overwrites)
channel = utils.get(categ.channels, name=str(message.author.id))
if not channel:
channel = await categ.create_text_channel(name=f"{message.author.id}", topic = str(message.author.id))
await channel.send(f"New Opened ModMail {message.author.mention})")
embed = discord.Embed(description=f"> {message.content}", timestamp=time.utcnow(), colour=discord.Colour.green())
embed.set_footer(text=message.author, icon_url=message.author.display_avatar.url)
await channel.send(embed=embed)```
@slate swan π
brooooo i keep getting indentation error
on__message??????????
bro dont tell me
please
@slate swan π
on__message?
π
A BIG F
f in the chatttttttttttttttt
xd
bro bro bro
thats why we tell to show full code π
rip
_ this thing wasted so much time 
xd
;+;
Bro according to the code all was ok
Except the _ ππ
Can someone help?
Just spit out the tea
Can someone help here
Hm
ireelevant from discord bots but why wont this specifc emoji appear in my roles π οΈ theres a different variation of it i dont like
Kinda messy on phone
Wdym?
from discord.ext import commands
client = commands.Bot(command_prefix="!", intents=discord.Intents.all())
@client.event
async def on_ready():
print("success Bot is connected to discord")
@client.command()
async def ping(ctx):
await ctx.send("pong!")
client.run("********************")```
[2022-12-13 22:07:20] [ERROR ] discord.ext.commands.bot: Ignoring exception in command None
discord.ext.commands.errors.CommandNotFound: Command "ping" is not found
i keep getting this
helped required
liek a different variation of the tool comes up
Hmm
from discord.ext
There is two spaces
@slate swan know a fix?
ohh
is asyncpg only useable with Postgresql? if so, is there other async drivers if I plan to use other DBs?
str(bot.command_prefix)
Try ig
await ctx.channel.delete()
is there a way to delete a thread with button?
yes
hey i need some help how do i make my bot create a file with a command?
Can someone help me please
i need help
yea
Traceback (most recent call last):
File "C:\Users\mrina\OneDrive\Documents\lib\site-packages\discord\client.py", line 627, in connect
await self.ws.poll_event()
File "C:\Users\mrina\OneDrive\Documents\lib\site-packages\discord\gateway.py", line 646, in poll_event
raise ConnectionClosed(self.socket, shard_id=self.shard_id, code=code) from None
discord.errors.ConnectionClosed: Shard ID None WebSocket closed with 1000
``` this error is coming whenever while loop repeats after `await asyncio.sleep(3600)`
@discord.ext.tasks.loop(*, seconds=..., minutes=..., hours=..., time=..., count=None, reconnect=True)```
A decorator that schedules a task in the background for you with optional reconnect logic. The decorator returns a [`Loop`](https://discordpy.readthedocs.io/en/latest/ext/tasks/index.html#discord.ext.tasks.Loop "discord.ext.tasks.Loop").
ok
He is always jumping to py if log_check is None: but log_check is not None
log_check = {'_id': 900100165397008465, 'global_id': 1049656196233175060, 'admin_id': 1026839897782366258, 'log_id': 1013596038071853157}
What
What is what?
Everything you have sent
what you do not understand?
Everything
Here is the Code
And here is the Problem
Now? @naive briar
if __name__ == "__main__":
async def main():
for cog in os.listdir("./cogs"):
if cog.endswith(".py"):
try:
cog = f"cogs.{cog.replace('.py', '')}"
await bot.load_extension(cog)
except Exception:
print(f"{cog} Can't be loaded")
raise Exception
async with bot:
bot.loop.create_task(create_db_pool())
change_presnce.start()
await bot.start(TOKEN)
asyncio.run(main())```
this is how i am starting the bot
but it won't respond to any commands
but the custom presence and custom prefix function `command_prefix=get_prefix` seem to run
and there are no errors in console
Did you turn message_content intent on
What does jumping even means
yes
and i have this in code intents = discord.Intents.all(),
that is, log_check is not None but it still goes to if log_ckeck is None:
it ignores the if log_check is not None
What
I'm not native speaker, but I know more than enough to understand programming questions
Lets see
Am I really the one who's making no sense here
You saw log_check right?
If it's not None then how can it jump to None?
π€·
Ig code got another brain to avoid ur commands π
I DON'T understand what jumping means
And you saw the if statements
if log_check is None and if log_check is not None
and we know that log_check is not None.And the problem is that he doesn't even notice the first if. And the first if statement is if log_check is not None
!e
input('Gib me your personal information')
@fossil sorrel :x: Your 3.11 eval job has completed with return code 1.
001 | Gib me your personal informationTraceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | EOFError: EOF when reading a line
Ok see
if .... is None:
...
if .... is not None:
!e
b = input('hi')
@fossil sorrel :x: Your 3.10 eval job has completed with return code 1.
001 | hiTraceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | EOFError: EOF when reading a line
For the love of God go to #bot-commands
He is meaning that, the ... Is Not None but it keeps going to None oarams
No
What?
What does that even mean
@white citrus u r code it like reversed π
Ok see
Don't flood the chat with bot commands for testing, use the #bot-commands channel.
Also, the eval command cannot receive input, so you are better off giving it a string value for testing
That means? xD
Code pls
I was testing the input.
Imma tell
@slate swan
Ok so according to u
The log_check is not None
But it's like bot understanding it's None?
Yeah
log_check = {'_id': 900100165397008465, 'global_id': 1049656196233175060, 'admin_id': 1026839897782366258, 'log_id': 1013596038071853157}
Does get_prefix return a prefix
if log_check is dict:
Check it π i don't think it's gonna work lmao
@naive briar helo me bruddah
But why in other cases it is also workung xD
!e
e ={}
if e is dict:
print(e)
@slate swan :warning: Your 3.11 eval job has completed with return code 0.
[No output]
@slate swan :x: Your 3.11 eval job has completed with return code 1.
001 | File "<string>", line 2
002 | if e is dict:
003 | ^
004 | IndentationError: expected an indented block after 'if' statement on line 2
It's isinstance
Ufff what am i doing
Yea me dying rn
but trying some new thing
Wait
!e
e=[]
if e is dict:
print('dict')
else:
print(';-;')
@slate swan :white_check_mark: Your 3.11 eval job has completed with return code 0.
;-;
I'm too tired to do anything
So in these lines:
case "show":
log_finder = {"_id": inter.guild.id}
log_check = await inter.client.settings.find(log_finder)
print(log_check)
It is printing the value of log_check?
Are there other cases that could be printing it and you are seeing that output instead?
@slate swan :white_check_mark: Your 3.11 eval job has completed with return code 0.
;-;
!d is
Makes sense
In a other case this is working and he go directly to if entry_true is not None:
entry_true = await inter.client.settings.find(settings_finder)
And log_check is the same thing
Yeah
Yeah to which question
It is printing the log_check
And to the secound question also yes
See here ^^
Well it turns out that an empty dictionary does not evaluate to None
No, it is not empty
log_check = {'_id': 900100165397008465, 'global_id': 1049656196233175060, 'admin_id': 1026839897782366258, 'log_id': 1013596038071853157}
Command or cog?
Maybe instead of testing if it is None, you could check if the length is 0
And just use an if / else instead of two ifs
Something like this maybe
...
if len(log_check) > 0:
if "log_id" in log_finder:
print("log_id passed")
...
else:
error = nextcord.Embed(title=f"{config.DiscordError} This guild has no log channel.", description="Please add a log channel",
colour=config.red)
await inter.response.send_message(embed=error, ephemeral=True)
Your code with the suggestion I made, with black run on it: https://paste.pythondiscord.com/dejuzanaxe
Lets go nextcord
Hey, what ping a role in embed ?
I have trying <@id>, <@&id>, <@{role}>
its <@&id>
Is not functional
that's the only way, mentions in discord embeds are messed up especially if you're on a mobile
I am on pc
ah
titles and embed fields dont allow mentions
oh...
you can use only description and field values for that
Ok thanks
reactions
im new to python and im trying to learn how to code a discord bot, the bot turns on but wont respond when I type the command
!intents ig
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.
if you have proper intents, then its probably an on_message event blocking ur commands
is this all new to python?
because I tried learning python like a year ago and I didint need this
how can i use RoleSelect in a form (model ) ?
you cant, and its a modal
so in a lot of bots, saying their prefix, lets say '+' and any invalid command, lets say 'blazing' = '+blazing' returns a response.
how would I do this?
I have no idea what you're asking
in a lot of bots if you use an invalid command, eg the prefix + a random word, it will return a specific response as a sort of invalid command catcher
when the start the bot on_ready fetch this message
Use on_command_error, handle commands.CommandNotFound
that's for application commands, isn't it?
I'm going for text commands, it's more my style
how do i make a set channel command? I know I could easily just do channel = bot.get_channel(ID) but, I want to make it to where you set it to a channel so I can possibly make a public bot. So I want it to be where you do /setchannel then you put the channel, then another command that sends a message to the channel that you set it to. I'm new to coding so idk how to do it
typehint the channel parameter as discord.TextChannel
no, thats not what im talking about, I'm trying to make it where i can set a channel without the ID.
read it again
its kinda like a logs channel but that doesnt send logs
How do you plan on getting the channel without it's ID?
You'll have to elaborate on what you mean by "put the channel"
idk how it works, i just seen other people do it on their bots
Do try to describe it.
example: theres a command where you set a channel by doing /setchannel then the channel, then it sends messages to that channel
its literally like if you were to set a logs channel
but without a webhook
You've already said that... but how do you want to choose the channel? You said it's not by typehinting to TextChannel, so what?
No?
thats not even possible with app_commands
heres a screenshot, idk how to explain it, you can put an ID or mention the channel
what we are trying to do?
Looks like just a regular old int typehint
then when you set it, for exampl the owner of the bot made the logs channel send applicatiosn
im trying to make a /setchannel command but like instead of using channel = bot.get_channel(ID) im trying to make it where you can change it by a command
if that makes sense
cause like im trying to make a public bot
and that wont work if i put an id cause multiple ppl will use it
So you don't want this?
for each server different channel?
I honestly still have no idea what you want. You vaguely said "put a channel" then you showed us a screenshot of what you don't want
thats a screenshot of what i do want
lol
So just use a regular int typehint and have the user enter their channel ID
yes, but like its a public bot, so multiple people will have it in their server and have different channels
So I've downloaded VSC in favor of Pycharm because I was told it would be easier to use as a beginner. I've downloaded a discord extension to get it to be able to import discord but I'm still having trouble getting it to work. Any thoughts?
You shouldn't be downloading any extensions to get discord.py to work
Extensions are for making VSCode itself behave in a certain way - not Python
It's just saying discord.py couldn't be resolved
Did you python -m pip install discord.py?
That brings up even more errors
Let's see them
