#discord-bots

1 messages Β· Page 154 of 1

shrewd apex
#

what do u think the ribble mark means ?

naive briar
#

Is that relevant to anything I'm saying πŸ€

slate swan
#

oh i js pinged wrong person mb

upbeat otter
#

bro, read the above conversation πŸ’€

shrewd apex
#

just use a modal

slate swan
#

it is

#

cant i just use wait for

cold sonnet
upbeat otter
#

good

slate swan
#

i have to add a try block

#

check if '#' on message.content or not

#

but idk where to add

slate swan
#

if not return shrug

regal cove
#
  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

slate swan
#
            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)```
naive briar
slate swan
#

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 #

naive briar
unkempt canyonBOT
#

@naive briar :white_check_mark: Your 3.11 eval job has completed with return code 0.

True
slate swan
slate swan
slate swan
tacit light
slate swan
regal cove
slate swan
naive briar
#

self is simply not defined 🀷

slate swan
#

means will do nothing

slate swan
slate swan
slate swan
#

....

#

how we gonna know tho πŸ’€

slate swan
#

im bugging

#

message.channel.send

#

We won't know unless you show the code

#

(remember to omit the token)

#

problem with the await

naive briar
#

!d discord.Client.wait_for

unkempt canyonBOT
#

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**...
upbeat otter
# slate swan

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

slate swan
#

oh lol

#

i totally forgot πŸ’€

regal cove
slate swan
#

msg = client.wait_for.....
if '#' in msg.content:
.....

slate swan
upbeat otter
slate swan
#

nah dawg

#

today my brain is dying

slate swan
slate swan
upbeat otter
slate swan
#

xdremove that line

#

no

slate swan
#

just use msg.content πŸ™‚

#

where client is waiting for a message

upbeat otter
#

just get the id within an argument while the command is being invoked

slate swan
#

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

#

πŸ™‚

naive briar
#

Then what is it

slate swan
#

i gib up πŸ™‚

#

i jsut need my bot to wait for 2 things

regal cove
#
@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"
slate swan
#

how do i add the second thing 😭

naive briar
regal cove
#

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'

naive briar
#

Read the error

#

You got your answer

slate swan
# naive briar lol

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 πŸ™‚

naive briar
#

There's something called on_message

slate swan
#

use modal = BEST

slate swan
naive briar
#

!d discord.on_message

unkempt canyonBOT
#

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.
slate swan
#

but it will always check for every msg tho

#

i cant have on_message i need it to be wait_for

slate swan
#

is there no way to edit wait_for to wait for 2 things

regal cove
# naive briar

i saw that but i dont understand what in my code was wrong

naive briar
naive briar
slate swan
#

it also makes sense

naive briar
#

Reading the error would also told you that

naive briar
#

Maybe

slate swan
#

MAYBE

#

it doesnt xd

regal cove
#

i will make sure to fix it

slate swan
#

cuz u cant check who interacted and whose message to check in on_message

#

so what do u think guys is it possible

slate swan
#

ez af

#

cant i just add a

#

if statement in my function

#

.....

#

@commands.has_permissions(administrator=True)

cold sonnet
#

wrong subject

slate swan
#

or

#

@commands.has_role()

naive briar
#

Huh

slate swan
#

only bot dev?

cold sonnet
#

!d discord.Guild.owner has got to exist

unkempt canyonBOT
slate swan
#

ez as that

cold sonnet
#

replace _ with .

#

I suppose

slate swan
cold sonnet
#

I dunno

slate swan
#

!d discord.Guild.owner_id

unkempt canyonBOT
naive briar
#

lol

slate swan
#

oh exist

cold sonnet
#

still exists, okay

#

use guild.owner instead

slate swan
#

xd

cold sonnet
#

if ctx.guild.owner == ctx.author?

slate swan
slate swan
slate swan
naive briar
slate swan
#

xd

#

@slate swan so dyk how i can do what im tryna do

naive briar
#

Do you even know what you're trying to do 🧐

frosty umbra
#

Biggest question in programming ^

slate swan
#

^

fading marlin
frosty umbra
slate swan
slate swan
regal cove
#
@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'

frosty umbra
slate swan
#

cause it will keep spamming messages when it detects that string buddy

frosty umbra
#

What do you mean

slate swan
frosty umbra
#

on message if channel = ticket

#

Psuedocode

slate swan
#

If you know what you're doing you're learning the wrong coding language

naive briar
naive briar
#

You should only add self if your function is in a class

slate swan
slate swan
fading marlin
#

Why is this the only channel where we don't have reaction perms

slate swan
#

wanna see it

#

might just use on_message fr

frosty umbra
frosty umbra
#

Who the heck is dracos LOL

slate swan
regal cove
slate swan
#

😭

frosty umbra
slate swan
frosty umbra
#

Daniel

slate swan
#

o

#

ok best coder is back πŸ’€

frosty umbra
#

i hope he aint payin u fo this 😭

#

Nah its cool

frosty umbra
#

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

cold sonnet
slate swan
#

kinda like day

frosty umbra
slate swan
frosty umbra
#

Lmao

slate swan
#

does it really exists? πŸ’€

frosty umbra
#

Its as real as the one piece 😈

#

THE ONE PIECE IS REAL

#

can we get much higher

slate swan
#

, i am dead

frosty umbra
#

Kekekekee

slate swan
#

dpy has like 40 solutions to my problem

slate swan
#

there all confusing tho

#

make slash command

#

to add member in ticket

frosty umbra
#

Not me saying this 30 minutes ago

#

I swear spooky just repeats what I say and its sounds more convincing

#

😭

frosty umbra
#

I have no clue what the # thing is about gonna need more detail to help

slate swan
slate swan
slate swan
#

can somone help me with my verification bot

#

I want it to listen to the dm for the verfication instead of everything

ember nest
#

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

cloud dawn
#

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.

ember nest
#

Nah but like I need an example on how it's possible to do

cloud dawn
#

channel could be none getch it first.

slate swan
cloud dawn
slate swan
#

the user uses the verify command

toxic loom
#

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?

cloud dawn
#
await interaction.followup.send(embed=embed)
slate swan
#

@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

cloud dawn
#

Well I only really want to solve coding errors right now.

#

Maybe someone else can go in depth on it.

slate swan
toxic loom
#

i got 20mins i can take a look if ya want

slate swan
cloud dawn
#

Full error?

slate swan
slate swan
fast lotus
#

after restarting the bot, tickets stop working. How to fix it ?

still basalt
#
@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?

full marten
#

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

unkempt canyonBOT
full marten
somber sky
#

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

austere vale
#
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?

slow zodiac
#

How do I create a dashboard?

sick birch
bright wedge
sick birch
bright wedge
bright wedge
bright wedge
sick birch
# slow zodiac overview

Sure.
My frontend was created with next tailwind typeScript - my favourite stack for any framework.
I use prisma as my Typescript ORM to interface with my backend database - postgreSQL
For the actual bot, I'll use python (90% of the time) or discord.js or serenity.rs rust

slow zodiac
bright wedge
sick birch
#

Oh and you'll want a REST API with logo_fastapi or logo_flask or logo_django2

#

Rocket + Diesel is the Rust alternative if you want that

slow zodiac
sick birch
#

The idea is to seperate your bot, frontend, and API

bright wedge
#

Its not easy but if you can't build a website (no full stack knowledge) build it in discord

sick birch
#

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

slow zodiac
#

oh

sick birch
#

It is quite a fun project to go with! I learned a bunch of different tools that way

bright wedge
# slow zodiac How are you going to create?

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.

slow zodiac
#

umm

#

But what do I do?

bright wedge
#

If you press one of theses options bot will create a channels called (option-tab)

#

Like (#music-tab or #moderation-tab etc).

slow zodiac
#

I'm Brazilian and I don't understand much English, I'm translating.

bright wedge
#

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)

sick birch
slow zodiac
#

I don't want to create a music bot I want to create a website where people can configure the bot.

bright wedge
#

That was a small preview of my dashboard,but as I said its not easy.

sick birch
#

Not as difficult as it may seem

bright wedge
#

To make you understand how the dashboard works

slow zodiac
#

AFK

#

OFF

bright wedge
#

Its like a mee6 dashboard but in discord.

hazy prawn
#

I need assistance.

bright wedge
hazy prawn
bright wedge
hazy prawn
#

I'm not familiar with python, is it just a simple code change or what

slow zodiac
#

I don't understand much python

#

:<

#

my name bot: Lena

hazy prawn
#

@bright wedge I just cant seem to figure out where client is defined twice and how to define the intents

slow zodiac
#

:<

unkempt canyonBOT
#

: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.

visual yarrow
#

!unmute 795672438708240448

unkempt canyonBOT
#

:incoming_envelope: :ok_hand: pardoned infraction mute for @slow zodiac.

slow zodiac
#

Hi

plain notch
#

Hi, I was wondering if I can please get some assistance on SQLite3, thank you!

slow zodiac
bright wedge
slow zodiac
#

I didn't understand?

bright wedge
slow zodiac
#

Will you help me create the dashboard? I wanted to know how you will help me.

slate swan
bright wedge
# ember nest

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.

slate swan
#

Some library supports that with ascii characters

slate swan
#

🀷

#

Idk if try

#

Ig

austere vale
# sick birch Can you show us the code for where the cog is being loaded?
@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()
sick birch
#

Your cog is loaded after the bot is ready

austere vale
sick birch
#

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

austere vale
#

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

sick birch
#

@austere vale move all of the stuff you have in on_ready into setup_hook, it'll fix both problems

austere vale
#

can you show me an example of how to use setup_hook?

sick birch
# austere vale 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(...)
slate swan
#

you can use ```py
bot = commands.Bot(...)

@bot.event
async def setup_hook():
...

austere vale
#

what would the difference between having subclass and not having subclass be? since this would go into main.py

sick birch
austere vale
# slate swan you can use ```py bot = commands.Bot(...) @bot.event async def setup_hook(): ...
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?

slate swan
#

you shouldnt have bot.wait_until_ready inside a setup hook

#

!d discord.Client.setup_hook

unkempt canyonBOT
#

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")...
slate swan
#

read the last warning

austere vale
#

ahh i see

#

im assuming i shouldnt be using awaits in it either ?

slate swan
#

you can use awaits, just not gateway things

austere vale
#

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

slate swan
#

if name == 'main': cause of this

#

actually that shouldnt matter hm

#

await bot.wait_until_ready()
did you remove this?

austere vale
#

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!'))
austere vale
#

do i need a login() somewhere?

slate swan
austere vale
#

i see, i'll try to change my code w ur feedback and make it work

#

thank u for helping!

drowsy zealot
#

what are the pros/cons to using nextcord, pycord or discord.py?

sick birch
robust fulcrum
#

Hi Robin

fast musk
#

I'm a d.py guy myself, but curious what makes pycord toxic

slate swan
# fast musk I'm a d.py guy myself, but curious what makes pycord toxic

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

sick birch
#

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

slate swan
#

agreed, definitely not beginner friendly πŸ’€

#

lol tbh they shit on other libraries more than forks do

fast musk
#

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

sick birch
#

But we go about it in a nicer way rather than just
"You suck at coding never try to code again"

fast musk
#

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"

slate swan
#

the famous ?tag lp

fast musk
#

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?

fast musk
#

timestamp vs joined_at

slate swan
#

message_content is required only for the text part of message, you still get the message objects

fast musk
#

oh ok, so I can still get on_message events?

slate swan
#

ofcourse!

fast musk
#

I thought those got silenced for some reason

slate swan
#

the message.content will just be None, thats all

fast musk
#

alright, so essentially on each event do an upsert in a small db with the timestamp?

slate swan
#

yeah that should work

fast musk
#

Am I right in thinking there is no built-in way?

slate swan
#

there is, but it will need a lot of API requests

#

!d discord.abc.Messageable.history

unkempt canyonBOT
#

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...
fast musk
#

yeah probably not ideal

slate swan
#

this iterates through the channel history, so you can find the user's last message

#

but that will be a heavy task

fast musk
#

granted pinging my sqlite db on each message isn't ideal either

#

heh... but probably more ideal than getting ratelimited

slate swan
# fast musk granted pinging my sqlite db on each message isn't ideal either

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

fast musk
#

yeah but if the bot crashes you do lose accuracy

slate swan
#

you do lose accuracy when the bot crashes anyhow lol

fast musk
#

Hah fair point.

vale wing
#

How to get contributors for bot 😩

naive briar
#

What kind

slate swan
#

allow bad commits πŸ’€πŸ—Ώ

slate swan
raw quail
#

hi guys. is there anyone using crawling/scraping bot for 24h on AWS EC2?

vale wing
slate swan
#

sarth, any good ways to learn db

#

sqlite
idk maybe suggest which is better

slate swan
slate swan
slate swan
#

any yt tutorial? XD

#

altho docs always better ngl

frosty umbra
#

SQL is relatively easy so SQLBolt might be better than a video

slate swan
#

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):

slate swan
#

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

slate swan
slate swan
#

still what to do no idea

#

GOT IT

#

YESSIR

dark sonnet
#

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

raw quail
#

uhjhjjjjjjjj im going to die

dark sonnet
#

hahaha

raw quail
#

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?

slate swan
#

if amount not int:
...

raw quail
#

other commands are working but only scraping command is not working. even not stop the bot with error

dark sonnet
raw quail
#
@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)
raw quail
slate swan
#

hmmmmmm any error?

raw quail
#

but when i send to discord, it's not working

#

NO ERROR just nothing happen on discord

slate swan
#

Whats the main problem rn

#

bot doesnt respond?

raw quail
#

that command is not working on AWS EC2.. so i am trying to find a reason all day haha

#

yeah exactly

slate swan
raw quail
#

just not respond. bot keep working without any error messages on discord and error code in terminal

slate swan
#

that is not our main thing to think xd

raw quail
#

yes

slate swan
#

does it print anything?

#

do u have on_message event?

raw quail
#

yes

#

this is other command when i type '=chart ticker'

raw quail
raw quail
#

even this simple command too.. when i write "ping" respond "pong!" well

slate swan
raw quail
#
@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

slate swan
#

ur process commands is inside in if statement

#

make it out side or use |
@bot.listen()

raw quail
#

oh

slate swan
# raw quail 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

raw quail
#

ohhhhhhh... wow

raw quail
slate swan
raw quail
slate swan
#

wait ur intents enabled?

raw quail
#

let me check

#
intents = discord.Intents.all()
slate swan
#

ok thats good

#

make sure to also enable on dev portal

raw quail
raw quail
#

ohhh thank you so much

raw quail
slate swan
#

u need to process commands

#

or use @bot.listen()
so bot can listen for prefix commands too

raw quail
#

Learning a lot from you . Thank you very much

slate swan
#

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

unkempt canyonBOT
#

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.
slate swan
slate swan
#

yes.

slate swan
slate swan
slate swan
#

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

slate swan
#

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):

slate swan
#

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

slate swan
#

if u really want to add --a use subcommand

#

ig

slate swan
slate swan
#

What I need is something like:```
!search [<--a> (optional, must say --a to count as the first arg)] <text>

slate swan
#

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

slate swan
#

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>

cloud dawn
#

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

slate swan
#

also there is no intents enabled

cloud dawn
raw quail
#
@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?

cloud dawn
#

Delete_after kwarg

raw quail
#

ohhhh

#

thank you so much

slate swan
#

like full code?

cloud dawn
slate swan
slate swan
north kindle
#

Hi, my bot printed this, what is it about and how can i fix it if it needs fixing

grand hazel
#

how to use the permission "Join server for you" in discordpy?

slate swan
#

u need to close the session btw

slate swan
#

guilds.join

#

scope

grand hazel
#

can you send me the sample code?

slate swan
grand hazel
#

;-; ok

north kindle
#

and when do we need to close it?

#

also, do i send the code here? its got some sensitive information such as passwords

slate swan
#

censor*

north kindle
#

!paste

unkempt canyonBOT
#

Pasting large amounts of code

If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/

After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.

slate swan
#

ok

north kindle
#

so basically this bot im using to fetch posts from reddit and send to discord

north kindle
#

yeah

slate swan
#

hmm

north kindle
#

its running on railway and works fine, but it printed those messages so i was wondering if i should be concerned

timid spade
#

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?

fast musk
#

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.

slate swan
timid spade
slate swan
#

not necessarily if you're able to take inputs with a prefix command that shouldn't be a problem

sullen roost
#

How do I transfer the written stuff in txt file to embed in a discord bot?

slate swan
#

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)

slate swan
#

sure

#

!print

#

!paste

unkempt canyonBOT
#

Pasting large amounts of code

If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/

After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.

slate swan
#

so?

#

round length isnt 44

slate swan
#

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

slate swan
#

I rlly havent coded in a long time

slate swan
#

wait I got my mistake

#

Can someone help me it says atributeerror: module 'discord' has no atribute 'bot'

#

good boy

unkempt canyonBOT
#

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.
slate swan
#

it shows this like

slate swan
slate swan
#

spooky plz help

slate swan
unkempt canyonBOT
#

Hey @slate swan!

You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.

slate swan
unkempt canyonBOT
#

Hey @slate swan!

You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.

slate swan
unkempt canyonBOT
#

Hey @slate swan!

You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.

slate swan
#

bro

#

@slate swan

slate swan
cold sonnet
#

you got it mate

slate swan
slate swan
#

not discord.bot

slate swan
slate swan
#

wtf is topic?

slate swan
slate swan
#

!d discord.Guild.create_category

unkempt canyonBOT
#

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`.
slate swan
#

need to give position

slate swan
slate swan
slate swan
unkempt canyonBOT
#

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.

slate swan
#

catg=guild.channels

#

category is a type of channel object

#

utils.get(guild.channels,..)

vale wing
#

Run black on this

slate swan
#

yes

slate swan
#

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

slate swan
#

bro

#

u r creating likewtf

#

what is again topic

unkempt canyonBOT
#

Hey @slate swan!

You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.

slate swan
#

is it forum channel

#

or what

slate swan
#

channel = await categ.create_text_channel(name=f"{message.author}", topic = str(message.author.id))

#

wth is this

#

ye

#

again what is topic? channel desc?

slate swan
slate swan
slate swan
#

ok

#

ok cool

#

....
name=str(...)

#

......

#

bruh

#

😭 im soooooooooo confused

slate swan
#

showing

#

@slate swan wdym u dont understand

#

remove this line

#

@slate swan

#

remove it?

#

yes

#

including the "bfroulette"

#

?

slate swan
#

now it says invalid syntax

slate swan
#

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 πŸ™‚

slate swan
vale wing
#

@slate swan what is your issue

slate swan
#

idk command just isnt working

vale wing
#

Send code

#

!code like this

unkempt canyonBOT
#

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.

slate swan
#

@vale wing

vale wing
#

Bro

#

The heck is that

slate swan
#

a bot

#

ohh thats how that works

vale wing
#
    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))

slate swan
#

uh

vale wing
#

Next

#

Do yk about elif existence

#

Next

#

Do yk about dictionaries

slate swan
#

LOL

slate swan
vale wing
#

That's required

sick birch
vale wing
#

Ikr

slate swan
#

ruh

#

bruh just help me fix it pls

#

im so confused

vale wing
#
if lastgame1 == "red":
        lastgame1 = "πŸŸ₯"
    if lastgame1 == "purple":
        lastgame1 = "πŸŸͺ"
    if lastgame1 == "yellow":
        lastgame1 = "🟨"```
To this
```py
d = {
  "red": "πŸŸ₯",
  "purple": "πŸŸͺ",
  "yellow": "🟨"
}
lastgame = d[lastgame]```
slate swan
#

ok

#

anything else?

vale wing
#
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
worldly portal
#

Hi
Please where can I find an API that gives updates on new altcoins that are launched

slate swan
#

ok

slate swan
vale wing
#

I am just trying to think how to optimize this hell

#

And whatever it's supposed to do

slate swan
#

LOL

slate swan
worldly portal
#

Been on that for the past hour

vale wing
#

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:]]
             ]```
worldly portal
vale wing
#

Useless yield

slate swan
#

it says indentation error now lol

vale wing
#

Indentation errors are easily solvable

slate swan
vale wing
shrewd apex
slate swan
#

ask melon musk to get some water from neptune

#

did u fix yet

#

πŸ™‚

vale wing
vale wing
slate swan
#

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
vale wing
#

To my knowledge flags are done differently

raw quail
#

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.
vale wing
raw quail
#

Ohhhhh thank you!!!

slate swan
#

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!")```
vale wing
slate swan
#

oh thanksss

arctic kindle
#

How can i check if a message is older then 2 Weeks?

vale wing
arctic kindle
#

TThx

slate swan
#
       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

#

xd

#

;+;

#

Bro according to the code all was ok

#

Except the _ πŸ˜‚πŸ˜‚

white citrus
#

Can someone help?

slate swan
#

Just spit out the tea

slate swan
#

U r genius dawg

white citrus
#

Can someone help here

slate swan
#

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

slate swan
#
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

slate swan
slate swan
slate swan
slate swan
#

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?

white aurora
#

yes

sullen roost
#

hey i need some help how do i make my bot create a file with a command?

white citrus
#

Can someone help me please

naive briar
#

What is that even mean

#

You're trying to make an extension?

sullen roost
steep estuary
#
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)`
naive briar
#

Use task loops instead

#

!d discord.ext.tasks.loop

unkempt canyonBOT
#

@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").
steep estuary
#

ok

white citrus
white citrus
naive briar
#

What

white citrus
naive briar
#

Everything you have sent

white citrus
naive briar
#

Everything

white citrus
white citrus
#

Now? @naive briar

split temple
#
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
naive briar
#

Did you turn message_content intent on

naive briar
split temple
#

yes
and i have this in code intents = discord.Intents.all(),

white citrus
#

it ignores the if log_check is not None

white citrus
#

Are you even speak English?

#

Or are you trolling?

naive briar
#

I'm not native speaker, but I know more than enough to understand programming questions

naive briar
#

Am I really the one who's making no sense here

white citrus
#

You saw log_check right?

slate swan
#

If it's not None then how can it jump to None?

#

🀷

#

Ig code got another brain to avoid ur commands πŸ˜‚

naive briar
#

I DON'T understand what jumping means

white citrus
# naive briar 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

fossil sorrel
#

!e
input('Gib me your personal information')

unkempt canyonBOT
#

@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
slate swan
#

if .... is None:
...
if .... is not None:

fossil sorrel
#

!e
b = input('hi')

unkempt canyonBOT
#

@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
naive briar
#

For the love of God go to #bot-commands

slate swan
#

He is meaning that, the ... Is Not None but it keeps going to None oarams

slate swan
#

Params

#

Wait.... Wth

fossil sorrel
#

What?

naive briar
slate swan
#

@white citrus u r code it like reversed πŸ˜‚

slate swan
velvet compass
# fossil sorrel No

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

white citrus
slate swan
slate swan
#

Imma tell

white citrus
slate swan
#

The log_check is not None

#

But it's like bot understanding it's None?

white citrus
#

Yeah

slate swan
#

@white citrus ded

#

Ok nice

#

What does log_check prints

white citrus
#

log_check = {'_id': 900100165397008465, 'global_id': 1049656196233175060, 'admin_id': 1026839897782366258, 'log_id': 1013596038071853157}

naive briar
slate swan
#

Check it πŸ’€ i don't think it's gonna work lmao

#

@naive briar helo me bruddah

white citrus
#

But why in other cases it is also workung xD

slate swan
#

!e
e ={}
if e is dict:
print(e)

unkempt canyonBOT
#

@slate swan :warning: Your 3.11 eval job has completed with return code 0.

[No output]
slate swan
#

!e=[]
if e is dict:

#

!e
e=[]
if e is dict:

unkempt canyonBOT
#

@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
vale wing
#

It's isinstance

slate swan
#

Ufff what am i doing

slate swan
#

but trying some new thing

#

Wait

#

!e
e=[]
if e is dict:
print('dict')
else:
print(';-;')

unkempt canyonBOT
#

@slate swan :white_check_mark: Your 3.11 eval job has completed with return code 0.

;-;
naive briar
slate swan
#

πŸ˜‚πŸ˜‚

#

!e
e={}
if e is dict:
print('dict')
else:
print(';-;')

velvet compass
# white citrus But why in other cases it is also workung xD

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?

unkempt canyonBOT
#

@slate swan :white_check_mark: Your 3.11 eval job has completed with return code 0.

;-;
naive briar
#

!d is

unkempt canyonBOT
#
is

6.10.3. Identity comparisons

The operators is and is not test for an object’s identity: x is y is true if and only if x and y are the same object. An Object’s identity is determined using the id() function. x is not y yields the inverse truth value. 4

slate swan
#

Makes sense

white citrus
#

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

velvet compass
white citrus
#

And to the secound question also yes

velvet compass
#

Well it turns out that an empty dictionary does not evaluate to None

white citrus
velvet compass
#

Could you share all of your code?

#

Instead of just the one case

white citrus
#

Command or cog?

velvet compass
#

Just the relevant part with this match case

#

So maybe just the match statement

white citrus
velvet compass
#

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)   
velvet compass
slate swan
#

Hey, what ping a role in embed ?

#

I have trying <@id>, <@&id>, <@{role}>

#

its <@&id>

slate swan
#

that's the only way, mentions in discord embeds are messed up especially if you're on a mobile

#

I am on pc

slate swan
#

ah

#

titles and embed fields dont allow mentions

#

oh...

#

you can use only description and field values for that

#

Ok thanks

fast lotus
versed token
#

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

slate swan
#

!intents ig

unkempt canyonBOT
#

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.

slate swan
#

if you have proper intents, then its probably an on_message event blocking ur commands

versed token
#

is this all new to python?

#

because I tried learning python like a year ago and I didint need this

marble rampart
#

how can i use RoleSelect in a form (model ) ?

slate swan
#

you cant, and its a modal

brisk dome
#

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?

upbeat gust
brisk dome
bright wedge
upbeat gust
brisk dome
#

I'm going for text commands, it's more my style

somber sky
#

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

glad cradle
somber sky
#

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

sick birch
#

You'll have to elaborate on what you mean by "put the channel"

somber sky
#

idk how it works, i just seen other people do it on their bots

sick birch
#

Do try to describe it.

somber sky
#

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

sick birch
upbeat gust
#

thats not even possible with app_commands

somber sky
sick birch
somber sky
#

then when you set it, for exampl the owner of the bot made the logs channel send applicatiosn

somber sky
#

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

bright wedge
#

for each server different channel?

sick birch
#

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

somber sky
#

lol

sick birch
#

So just use a regular int typehint and have the user enter their channel ID

somber sky
#

yes, but like its a public bot, so multiple people will have it in their server and have different channels

sick birch
#

And the users will enter their respective channel ID

#

Everyone is happy

mortal pivot
#

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?

sick birch
#

Extensions are for making VSCode itself behave in a certain way - not Python

mortal pivot
sick birch
mortal pivot
sick birch
#

Let's see them

mortal pivot