#discord-bots

1 messages · Page 139 of 1

slate swan
#

bc its adds one when they check in the db if there is a warning

#

so at first he sees 0

#

side note: instead of py warnnum = 0 for table in data: warnnum += 1 you can do ```py
for warnum, table in enumerate(data, start=1):

#

oh

#

thats a way too

potent spear
slate swan
#

like if they do smt

potent spear
#

yeah, and it counts the amount of previous warnings in the db?

#

tell me the whole logic of your warns command and how it's connected to your db, I'll wait

#

example
my warns command warns a member with a given reason
first it checks the db if he doesn't have more than x warnings already
if he does, kick, if he doesn't add the warning with the reason to the db and send a message...

slate swan
potent spear
#

so, show me your code again

slate swan
#

!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
potent spear
#

alright, first issue here is that you're using on_ready for api calls etc, you should use startup tasks
but that's not the issue here

#

so the warns command should only check the warnings a certain member has?

slate swan
#

yes

potent spear
#

alright, now we're getting somewhere

slate swan
#

🙂

potent spear
#

can you print data for me?

#

right after you fetched it

slate swan
#

yes

slate swan
potent spear
#

alright, so you get a tuple returned

#

so table[1] should work fine, you don't need to int() that, since it's already an int

slate swan
#

oh okay

potent spear
#

try and see

slate swan
#

okaay

#

nextcord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: 'int' object is not subscriptable

potent spear
#

whenever you send those kind of lines
I always want to see full traceback and also your current code in that command from now on

slate swan
#

oh okay

potent spear
#

preferably with a note where that line is

#

since I can't see line numbers in codeblocks on discord

slate swan
#
Ignoring exception in on_command_error
Traceback (most recent call last):
  File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\ext\commands\core.py", line 165, in wrapped
    ret = await coro(*args, **kwargs)
  File "c:\Users\PC\Desktop\Aleccy Bot\main.py", line 96, in warns
    em.add_field(name=f"Warning {warnnum}", value=f"Reason: {table[0]} | Date: <t:{table[1]}:F>")
TypeError: 'int' object is not subscriptable

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\client.py", line 502, in _run_event
    await coro(*args, **kwargs)
  File "c:\Users\PC\Desktop\Aleccy Bot\main.py", line 605, in on_command_error
    raise error
  File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\ext\commands\bot.py", line 1382, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\ext\commands\core.py", line 948, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\ext\commands\core.py", line 174, in wrapped
    raise CommandInvokeError(exc) from exc
nextcord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: 'int' object is not subscriptable```

```                    em.add_field(name=f"Warning {warnnum}", value=f"Reason: {table[0]} | Date: <t:{table[1]}:F>")

line 96

potent spear
#

you printed data above that, right?

slate swan
#

yes

#

('No reason provided', 1668948772)

potent spear
#

can you do cursor.fetchall() instead of fetchone()?

slate swan
#

oh yeah

potent spear
#

check if that changes anything

slate swan
#

WORKS

#

OMG TYSM

potent spear
#

alr, there's multiple other optimization issues with that code, but Ig that's not your main issue

slate swan
#

yep!

potent spear
#

your main optimization would be to not use on_ready for changing your presence and starting your db

slate swan
#

oh

#

thats also good

#

bot = discord.Bot(intents=intents)
AttributeError: module 'discord' has no attribute 'Bot' help

#
bot = discord.Bot(intents=intents)
AttributeError: module 'discord' has no attribute 'Bot'
``` can someone help me? i've been strugling on this error for like 30 mins...
cloud dawn
#

You are following a py-cord tutorial, it's discord.ext.commands.Bot

shrewd apex
#

💀

ocean hawk
#

Someone grabbed my discord token cause they thought it was malicious i need help to prevent this from happening(the closest thing that my discord bot has to malicious is deleting messages that have bad words)

fading marlin
#

don't leak your token then?

ocean hawk
fading marlin
#

apparently you did, because someone uploaded it to github so it would get automatically invalidated for you

shrewd apex
gleaming thicket
#

Hey guys

#

who would be able to make me a discord bot with just 1 "application command" so i can get the developer badge for $10 paypal

upbeat otter
#

!rule 9

unkempt canyonBOT
#

9. Do not offer or ask for paid work of any kind.

upbeat otter
#

I'd die about the ten dollars
💀 10 dollars for a badge

sick birch
#

Badge don't even work

#

I have plenty of bots but don't have the badge

upbeat otter
#

which badge though
lmao

gleaming thicket
sick birch
gleaming thicket
#

is there other requirements?

sick birch
#

Don't think so

#

It's pretty open in terms of requirements

gleaming thicket
#

i alrdy have a bot but its developed in old asf python

#

and they didnt update that api im pretty sure

#

and it doesnt have any application commands lmao

sick birch
#

Your bots slash command needs to be executed in the last 30 days I believe

gleaming thicket
#

made it like 3 years ago

sick birch
#

That's the only requirement

gleaming thicket
#

yep thats fine

#

Your app is missing an invite link. Add one so users can add your bot to their server easily.

#

where the hell do i add this lmao

#

is there any easy way to check how many servers my discord bot is in?

ocean hawk
shrewd apex
upbeat otter
zealous jay
#

A bot that plays music from youtube is no longer allowed even if its only in my server?

upbeat otter
slate swan
#

default_role is everyone ?

zealous jay
#

So, if I want to keep my account alive its a no

mental hollow
slate swan
#

thanks

mental hollow
#

:)

upbeat otter
zealous jay
#

and discord?

upbeat otter
#

discord music bots were based on the fact that they used youtube_dl
so the popular music bots you see, most of them still use youtube_dl

zealous jay
#

hm

#

Idk I don't want my account to get banned somehow

#

and the server

upbeat otter
#

I don't think it should

#

but no comments

slate swan
#

does anyone have ideas to what i can add to my public bot?

sick birch
#

Not even worth your time

slate swan
#

i rlly dont know

turbid totem
#

Hi I have a noob question
I have all my commands in a one main.py file
Would it make much difference if i carry on like this rather than adding them to cogs ( i still have no idea how to do it )? Would it make it faster or it’s just more organized

naive briar
#

It's more organized

turbid totem
#

Okay thankss

potent spear
#

I don't have any bot running on v2, so there's that

slate swan
#

the active developer badge required less efforts than a hypesquad badge to claim kek

slate swan
slate swan
#

im lazy to open vs code and create a bot app 😩

slate swan
sick birch
#

¯_(ツ)_/¯

torn sail
#

how do u even get the badge?

slate swan
#

what's the best way to organize cogs

#

a cog for one command? one cog for a command category?

cloud dawn
#

Commands that belong together.

slate swan
shrewd apex
slate swan
#

will splitting to file per command affect the performance?

fading marlin
#

it'll just look messy

glad cradle
violet kraken
#

Uh

slate swan
#

k

slate swan
#

I have a parameter called colour and a variable called yellow. This code:

if yellow==colour:
   await guild.create_role(name=f'{name}', color=yellow)```

doesnt work and the issue is in the `if`. Why?
#

What i want to do is if the yellow is the colour parameter, to create a role with yellow color

#

what is your yellow variable? and how do you parse the colour var

primal token
shrewd apex
#

discord mobile as usualpithink

nimble timber
#

Can anyone tell me why I can't download the pip command?

slate swan
#

my commands don't run ! i don't have a on_message event

#

is it possible it's for a while loop in the on_ready event ?

cloud dawn
slate swan
#

its uglier than the old one

cloud dawn
#

Well tastes differ.

#

Besides the other one I had for 2 years.

slate swan
#

old one is making u a chad

cloud dawn
#

I like to switch it up after a year or 2

slate swan
#

k

slate swan
#

bruh

sick birch
nimble timber
#

error: subprocess-exited-with-error
exit code: 1
╰─> [126 lines of output]
error: legacy-install-failure
This is an issue with the package mentioned above, not pip.
hint: See above for output from the failu

#

Guys, I'm typing pip Install disco.py and it gives an error

slate swan
slate swan
#

where are the wait for docs?

#

!waitfor

#

?wait_for

primal token
#

!d discord.ext.commands.Bot.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**...
keen vault
#

Someone help?

slate swan
#

seems like broken python install, it was just a Literal use

keen vault
#

how do I fix it?

slate swan
austere vale
#

could someone help me with this error please?

0|Runa     |     ret = await coro(*args, **kwargs)
0|Runa     |   File "/home/Runa/bot/cogs/giveaway.py", line 118, in giveaway
0|Runa     |     if time == -1:
0|Runa     | TypeError: convert() takes 1 positional argument but 2 were given
0|Runa     | 
0|Runa     | The above exception was the direct cause of the following exception:
0|Runa     | 
0|Runa     | Traceback (most recent call last):
0|Runa     |   File "/usr/local/lib/python3.8/dist-packages/nextcord/ext/commands/bot.py", line 1382, in invoke
0|Runa     |     await ctx.command.invoke(ctx)
0|Runa     |   File "/usr/local/lib/python3.8/dist-packages/nextcord/ext/commands/core.py", line 948, in invoke
0|Runa     |     await injected(*ctx.args, **ctx.kwargs)
0|Runa     |   File "/usr/local/lib/python3.8/dist-packages/nextcord/ext/commands/core.py", line 174, in wrapped
0|Runa     |     raise CommandInvokeError(exc) from exc
0|Runa     | nextcord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: convert() takes 1 positional argument but 2 were given

code:

  #convert time into something typable
  def convert(time):
    pos = ["s","m","h","d"]
    time_dict = {"s" : 1, "m" : 60, "h" : 3600, "d": 3600*24}
    unit = time[-1]
    if unit not in pos:
      return -1
    try:
      val = int(time[:-1])
    except:
      return -2
    return val * time_dict[unit]
  #giveaway command
  @commands.command()
  @commands.has_permissions(kick_members=True)
  async def giveaway(self,ctx):
    await ctx.send("Let's start with this giveaway! Answer these questions within 15 seconds!")
    questions = ["Which channel should it be hosted in?", "What should be the duration of the giveaway? (s|m|h|d)", "What is the prize of the giveaway?"]
    answers = []
    def check(m):
      return m.author == ctx.author and m.channel == ctx.channel
    for i in questions:
      await ctx.send(i)
      try:
        msg = await self.bot.wait_for('message', timeout=15.0, check=check)
      except asyncio.TimeoutError:
        await ctx.send('You didn\'t answer in time, please be quicker next time!')
        return
      else: 
        answers.append(msg.content)
    try:
      c_id = int(answers[0][2:-1])
    except:
      await ctx.send(f"You didn't mention a channel properly. Do it like this {ctx.channel.mention} next time.")
      return
    channel = self.bot.get_channel(c_id)
    time = self.convert(answers[1])
    if time == -1:
      await ctx.send(f"You didn't answer with a proper unit. Use (s|m|h|d) next time!")
      return
    elif time == -2:
      await ctx.send(f"The time just be an integer. Please enter an integer next time.")
      return
    prize = answers[2]
    await ctx.send(f"The giveaway will be in {channel.mention} and will last {answers[1]} seconds!")
    embed = nextcord.Embed(title = "Giveaway!", description = f"{prize}", color = ctx.author.color)
    embed.add_field(name = "Hosted by:", value = ctx.author.mention)
    embed.set_footer(text = f"Ends {answers[1]} from now!")
    my_msg = await channel.send(embed = embed)
    await my_msg.add_reaction("🎉")
    await asyncio.sleep(time)
    new_msg = await channel.fetch_message(my_msg.id)
    users = await new_msg.reactions[0].users().flatten()
    users.pop(users.index(self.bot.user))
    winner = random.choice(users)
    await channel.send(f"Congratulations! {winner.mention} won the prize: {prize}!")
north pecan
#

val = int(time[:-1]) thats on a list

#

not a single item, here you're splicing not indexing

#

unless its a string?

#

oops wrong area hold on

austere vale
#

oh wait, nevermind! i added self as a parameter to convert() and it seems to be fixed

north pecan
#

yeah doesnt look like its in a class

austere vale
#

thank you so much though

north pecan
#

however you can make discord bots in a class lol

austere vale
#

yeye

desert badger
#

how do i get a timestamp for "in 24 hours"

#
await channel.send(f"Restart in {24 hour timestamp}")
kind trellis
shadow vigil
#

my friend you should learn the basics of programming

#

i am the type that old/young doesn't matter

upbeat gust
#

😳

shadow vigil
#

i have no comment...

steel pebble
#

does anyone know how to pull old usernames?

kind trellis
bright wedge
kind trellis
#

Resolved

slate swan
#

Hello! How do I handle optional args? I am trying to make it so if there is no argument, (if arg is None) it does one thing or else does another.

#

I have before the arg so *arg and have it so if arg is None: and then an else statement, but it does not seem to be working.

#

@sick birch you think you can please help? 🙂

shrewd apex
#

send code

slate swan
bright wedge
#

you can do something like that

bright wedge
slate swan
#

So the * makes the next arg optional?

#

Why not *arg

restive spoke
#

Hello, is it possible for discord bot to?

  1. Find certain image from the inventory - screenshot upload to the bot
  2. Detect the quantity of the item
  3. Detect the price, and show the price based on the quantity
  4. Total all the assets in the inventory
shrewd apex
#

= None does that

bright wedge
restive spoke
#

Well good to know then

bright wedge
bright wedge
restive spoke
#

Time to start from the base.

sick birch
restive spoke
#

Basically inventory from a game, let me screenshot example of the inventory

#

The plan was to detect the amount of the item in the inventory and then it tell you the total price for it. Something like that

#

Not sure if that works or not, It just for test.

shrewd apex
#

the numbers can be figured out easily but differentiating between blocks and telling them apart will be tough and kinda complex

restive spoke
#

Yeah, that's what I'm thinking.

shrewd apex
#

most probable way is to identify is based on colour u will prolly need opencv but operations like this will prolly be resource consuming not economical for a discord bot

restive spoke
#

Well this main question was in general chat but it just ignored so I asked in here.

#

Anyways, I already done half of this so no worries.

slate swan
shrewd apex
# slate swan So what’s the * for before?

in general python * indicates following arg as a kwarg but in dpy its basically indicates the next arg to be a greedy arg and consume everything passed in the function from that param onwards

slate swan
bright wedge
restive spoke
#

Oh? That's interesting

bright wedge
#
{
  "image_url": "1253",
  "image_url": "6346",
 "image_url": "8615"

}
#

i have story the items in json file like that (image_url must be the key because is unique (cant have 2 records with same key)

#

after that using PIL i take this data and return it to inventory items with amount ! (key for image_url and value for amount)

#

you can create and pages if you have many items!

slate swan
shrewd apex
shrewd apex
slate swan
#
    @nextcord.ui.button(label=":newspaper:", custom_id="paper")
    async def paper(self, button:nextcord.ui.Button, interaction: nextcord.Interaction):
        if not interaction.user:
            return await interaction.response.send_message(content="Thats not your button!", ephemeral=True)
        if interaction.user:
            return await interaction.response.send_message(content="Choosed paper.", ephemeral=True)
        await interaction.response.send_message(view=rpsView())```
when another user that didnt start the rps game tapping on the button it doesnt response Thats not your button! its saying Choosed paper.
#

w no error

bright wedge
slate swan
#

oh

#

wait

bright wedge
#

so what are you checking for? xd?

slate swan
#

so how do i take the one who did the command

glad cradle
slate swan
#

yes

bright wedge
glad cradle
#

so you can pass the interaction of the command when you send the first response to the slash command

the __init__ of your view subclass should accept an argument such as (for example) original_interaction and save it as class variable (self.original_interaction = original_interaction) the only thing you will have to do is pass the original interaction when creating the object of your custom view

await interaction.response.send_message(view=MyView(interaction))

slate swan
#

omg thank you so much!!

slate swan
# bright wedge show me your command that call the paper view

@nextcord.ui.button(label="📰", custom_id="paper")
async def paper(self, button:nextcord.ui.Button, interaction: nextcord.Interaction):
if interaction.user:
return await interaction.response.send_message(content="Choosed paper.", ephemeral=True)
await interaction.response.send_message(view=rpsView())

bright wedge
#

in ` please

#

this is the button

#

i want the command!

slate swan
#

oh okay

glad cradle
#

Another way could be to get the original message but in the way I sent you'll save a useless API call

slate swan
#
@bot.command()
async def rps(ctx):
    view = rpsView()
    em = nextcord.Embed(title=f"Rps Game", description="Choose one of these options. \n :newspaper: Paper\n:new_moon: Rock\n:scissors: Scissors", color=0xfff8b0)
    await ctx.send(embed=em, view=view)```
slate swan
bright wedge
#
@bot.command()
async def rps(ctx):
    view = rpsView()
    em = nextcord.Embed(title=f"Rps Game", description="Choose one of these options. \n :newspaper: Paper\n:new_moon: Rock\n:scissors: Scissors", color=0xfff8b0)
    await ctx.send(embed=em, view=view(ctx.author))
slate swan
#

oh

bright wedge
#

you gonna pass the ctx.author (the user who can use the interaction)

#

you will define the user in your button class

#

like self.author=author

#

and then do the check

if interaction.user == self.author
glad cradle
#

I would pass the entire ctx object so that in its class he can access what he wants without problems

bright wedge
glad cradle
#

Also it would be better to use ids, names and tags can change

slate swan
#

ill try

bright wedge
slate swan
#

yes

#

also now its doing that when another user pressed the button

bright wedge
slate swan
#
class rpsView(nextcord.ui.View):
    def __init__(self, author):   
        super().__init__(timeout=None) 
        self.author=author```
bright wedge
#
class rpsView(nextcord.ui.View):
    def __init__(self, author:discord.Member):   
        super().__init__(timeout=None) 
        self.author=author

    @nextcord.ui.button(label=":newspaper:", custom_id="paper")
    async def paper(self, button:nextcord.ui.Button, interaction: nextcord.Interaction):
        if interaction.user == self.author:
            await interaction.response.send_message(content="Choosed paper.", ephemeral=True,view=rpsView())

slate swan
#

oh

#

ill try now

slate swan
bright wedge
#

let me test it

glad cradle
#

no you need to initialize the view in your command body

#
@bot.command()
async def rps(ctx):
    view = rpsView(ctx)
    em = nextcord.Embed(title=f"Rps Game", description="Choose one of these options. \n :newspaper: Paper\n:new_moon: Rock\n:scissors: Scissors", color=0xfff8b0)
    await ctx.send(embed=em, view=view)```
glad cradle
#

also compare ids not names

slate swan
#

i will change it later okay

bright wedge
glad cradle
#

username + tag

slate swan
#

oh i gtg to school

#

thank u both!

glad cradle
bright wedge
glad cradle
slate swan
#

but ill fix it

#

byee

bright wedge
slate swan
#

Oh ill try it when ill be back home

#

Thank you!

bright wedge
# slate swan Thank you!
#Button Class
class rpsView(discord.ui.View):
    def __init__(self, author:discord.Member):   
        super().__init__(timeout=None) 
        self.author=author

    @discord.ui.button(label=":newspaper:", custom_id="paper")
    async def paper(self, interaction: discord.Interaction, button: discord.ui.Button):
        if interaction.user == self.author:
            await interaction.response.send_message(content="Choosed paper.", ephemeral=True)

#Cog Class
class Test(commands.Cog):

    def __init__(self, bot):
        self.bot = bot   
        bot.add_view(rpsView(None)) #None parameter for ctx.author

    @commands.command()
    async def rps(self,ctx):
        view = rpsView(ctx)
        em = discord.Embed(title=f"Rps Game", description="Choose one of these options. \n :newspaper: Paper\n:new_moon: Rock\n:scissors: Scissors", color=0xfff8b0)
        await ctx.send(embed=em,view=rpsView(ctx.author))


async def setup(bot):
    await bot.add_cog(Test(bot))
#

this is cog file btw!

slate swan
#

Oh thats better!

#

Tysm!!!

bright wedge
#

and change this version to yours (nextcord)

slate swan
#

Yeah

bright wedge
#

Good lesson

slate swan
#

Haha

sly fractal
#

please help with this error ;-;

bright wedge
sly fractal
#

nope

#

i changed it to the one for this server?

frosty cape
#

yay

sly fractal
#

but what i got banned from discord?

bright wedge
#

you are trying to abuse something

slate swan
#

how do i make a copy button, so when the user presses the button, it sends 2 messages containing the content under “BTC value amount” and “payment address”

shrewd apex
shrewd apex
slate swan
shrewd apex
#

no idea

shrewd apex
#

also discord bans bots from currency stuff from the latest toc stuff

#

especially games like gambling currency exchange and stuff

slate swan
bright wedge
#

wdym copy?

slate swan
# bright wedge wdym copy?

like it sends 2 messages containing the value in “btc value amount” and “payment address” when i press the button

bright wedge
slate swan
sweet pilot
#

is there any way i could get emoji ids

#

i want to react with ⬆️ to a message

#

with arrow_up words

naive briar
#

Just

:arrow_up: ```
sweet pilot
#

k but await message.add_reaction(":arrow_up") doesn't work

naive briar
shrewd apex
#

or even the standard emoji is fine like just ⬆️

slate swan
sweet pilot
naive briar
#

What are you trying to do exactly

naive briar
unkempt canyonBOT
#

class discord.ButtonStyle```
Represents the style of the button component.

New in version 2.0.
sweet pilot
#

wanna put an upvote to a msg

#

i am able to do it

#

but

frail tapir
#

just put the emoji instead of all that

sweet pilot
#

did tht

#

it's the whole problem

#

when i go to reactions and click ⬆️ it is recognized as another emoji

#

rather than the one added from the bot

upbeat gust
#

you need to use the unicode form

#

And variation selector 16

#

Ugh it's smth like that lemme see

sweet pilot
#

see

slate swan
sweet pilot
#

the same upvote but recognized as 2 emojis

upbeat gust
#

use these unicode codes

#

@sweet pilot

upbeat gust
sweet pilot
upbeat gust
#

Yes

slate swan
#

why does my copy button not work

naive briar
#

Give better explanation

upbeat gust
#

We can't read your mind

trim shadow
#

hello

#

i am use webhook.send(), how to get id this message

naive briar
#

!d discord.Webhook.send - it returns WebhookMessage object. Just get the ID with .id from it

unkempt canyonBOT
#
await send(content=..., *, username=..., avatar_url=..., tts=False, ephemeral=False, file=..., files=..., embed=..., embeds=..., allowed_mentions=..., view=..., thread=..., ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Sends a message using the webhook.

The content must be a type that can convert to a string through `str(content)`.

To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File "discord.File") object.

If the `embed` parameter is provided, it must be of type [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") and it must be a rich embed type. You cannot mix the `embed` parameter with the `embeds` parameter, which must be a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.11)") of [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") objects to send.

Changed in version 2.0: This function will now raise [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError "(in Python v3.11)") instead of `InvalidArgument`.
slate swan
#

Theres that thing in some bits that they want access to our account how do i add it on my bot?

trim shadow
naive briar
#

!d aiohttp.ClientSession

unkempt canyonBOT
#
class aiohttp.ClientSession(base_url=None, *, connector=None, cookies=None, headers=None, skip_auto_headers=None, auth=None, json_serialize=json.dumps, ...)```
The class for creating client sessions and making requests.
trim shadow
# naive briar !d aiohttp.ClientSession

like that ? ```py async def main():
async with ClientSession() as session:
webhook = Webhook.from_url(webhook_url, session=session)
ress = await webhook.send(content="123")
pprint(ress)

if name == "main":
asyncio.run(main())```

naive briar
#

Yes

trim shadow
# naive briar Yes

output py None Exception ignored in: <function _ProactorBasePipeTransport.__del__ at 0x00000218CDE4B3A0> Traceback (most recent call last): File "E:\Python\Python39\lib\asyncio\proactor_events.py", line 116, in __del__ self.close() File "E:\Python\Python39\lib\asyncio\proactor_events.py", line 108, in close self._loop.call_soon(self._call_connection_lost, None) File "E:\Python\Python39\lib\asyncio\base_events.py", line 746, in call_soon self._check_closed() File "E:\Python\Python39\lib\asyncio\base_events.py", line 510, in _check_closed raise RuntimeError('Event loop is closed') RuntimeError: Event loop is closed

trim shadow
naive briar
#

Try setting the event loop policy with

asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())

On top of your asyncio.run

trim shadow
naive briar
#

Set the wait argument to True

trim shadow
#

thanks!

slate swan
naive briar
#

!intents

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.

whole sparrow
#

guys is there a reason why this happens on mobile but its fine on pc

#

the command mention

naive briar
#

Try updating your Discord

slate swan
# bright wedge ```py #Button Class class rpsView(discord.ui.View): def __init__(self, autho...
  File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\ext\commands\bot.py", line 800, in _load_from_module_spec
    setup(self, **extras)
  File "c:\Users\PC\Desktop\Aleccy Bot\cogs\rps.py", line 31, in setup
    bot.add_cog(Test(bot)) 
  File "c:\Users\PC\Desktop\Aleccy Bot\cogs\rps.py", line 21, in __init__
    bot.add_view(rpsView(None)) #None parameter for ctx.author
  File "c:\Users\PC\Desktop\Aleccy Bot\cogs\rps.py", line 8, in __init__
    super().__init__(timeout=None) 
  File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\ui\view.py", line 190, in __init__
    loop = asyncio.get_running_loop()
RuntimeError: no running event loop

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "c:\Users\PC\Desktop\Aleccy Bot\main.py", line 48, in <module>
    bot.load_extension(f"cogs.{fn[:-3]}")
  File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\ext\commands\bot.py", line 888, in load_extension
    self._load_from_module_spec(spec, name, extras=extras)
  File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\ext\commands\bot.py", line 805, in _load_from_module_spec
    raise errors.ExtensionFailed(key, e) from e
nextcord.ext.commands.errors.ExtensionFailed: Extension 'cogs.rps' raised an error: RuntimeError: no running event loop```
slate swan
#

okay

bright wedge
#

You need asyn function to load the extensions

slate swan
#

i did it on the main file

#

it works

bright wedge
#

await asyncio.run(your async function)

#

So everything is ok?

slate swan
#

yes!

bright wedge
#

Good

slate swan
#

tysmm!

bright wedge
#

Remember,the buttons are not working after the bot restart.

slate swan
#

yeah ik how to fix it

#

tysm

bright wedge
slate swan
#

tyyy

loud junco
#

can anyone help with my discord bot's database in #databases 🥹

sweet pilot
#

how can i get the msg from id

vocal snow
unkempt canyonBOT
#

await fetch_message(id, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Retrieves a single [`Message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message "discord.Message") from the destination.
loud junco
sweet pilot
#

had to use Bot.get_channel to get the channel

upbeat otter
loud junco
upbeat otter
loud junco
slate swan
#

await cursor.execute("DELETE FROM afk WHERE user = ? AND guild = ?", (author.id, guild.id,))
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\aiosqlite\cursor.py", line 37, in execute
await self._execute(self._cursor.execute, sql, parameters)
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\aiosqlite\cursor.py", line 31, in _execute
return await self._conn._execute(fn, *args, **kwargs)
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\aiosqlite\core.py", line 129, in _execute
return await future
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\aiosqlite\core.py", line 102, in run
result = function()
sqlite3.OperationalError: database is locked

#

sending everythinmg twice or 3 times

cloud dawn
#

You have the bot running 3 times most likely

slate swan
#

i dont thats weird

#

ill try restarting the token again

cloud dawn
#

Check task manager.

slate swan
#
Traceback (most recent call last):
  File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\client.py", line 502, in _run_event
    await coro(*args, **kwargs)
  File "c:\Users\PC\Desktop\Aleccy Bot\main.py", line 34, in on_ready
    await cursor.execute("CREATE TABLE IF NOT EXISTS levels (level INTEGER, xp INTEGER, user INTEGER, guild INTEGER)")
  File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\aiosqlite\cursor.py", line 37, in execute
    await self._execute(self._cursor.execute, sql, parameters)
  File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\aiosqlite\cursor.py", line 31, in _execute
    return await self._conn._execute(fn, *args, **kwargs)
  File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\aiosqlite\core.py", line 129, in _execute
    return await future
  File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\aiosqlite\core.py", line 102, in run
    result = function()
sqlite3.OperationalError: database is locked```
cloud dawn
#

Did you check task manager?

slate swan
#

Someone help

shrewd apex
slate swan
#

It’s enabled

shrewd apex
slate swan
cloud dawn
naive briar
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
#
@bot.event
async def on_ready():
    print(f"{bot.user.name} is online!")
    setattr(bot, "db", await aiosqlite.connect("levels.db"))
    async with bot.db.cursor() as cursor:
        await cursor.execute("CREATE TABLE IF NOT EXISTS levels (level INTEGER, xp INTEGER, user INTEGER, guild INTEGER)")
        await cursor.execute("CREATE TABLE IF NOT EXISTS levelSettings (levelsys BOOL, role INTEGER, levelreq INTEGER, guild INTEGERP)")
        await cursor.execute("CREATE TABLE IF NOT EXISTS afk (user INTEGER, guild INTEGER, reason TEXT)")
        await cursor.execute("CREATE TABLE IF NOT EXISTS warns (user INTEGER, reason TEXT, time INTEGER, guild INTEGER)")
    

async def addwarn(ctx, reason, user):
    async with bot.db.cursor() as cursor:
        await cursor.execute("INSERT INTO warns (user, reason, time, guild) VALUES (?, ?, ?, ?)", (user.id, reason, int(datetime.now().timestamp()), ctx.guild.id,))
    await bot.db.commit()
#

OH GOT IT

#

INTEGERP

#

nvm that wasnt the problem

#

Traceback (most recent call last):
  File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\ext\commands\core.py", line 165, in wrapped
    ret = await coro(*args, **kwargs)
  File "c:\Users\PC\Desktop\Aleccy Bot\main.py", line 148, in afk
    await cursor.execute("INSERT INTO afk (user, guild, reason) VALUES (?, ?, ?)", (ctx.author.id, ctx.guild.id, reason,))
  File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\aiosqlite\cursor.py", line 37, in execute
    await self._execute(self._cursor.execute, sql, parameters)
  File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\aiosqlite\cursor.py", line 31, in _execute
    return await self._conn._execute(fn, *args, **kwargs)
  File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\aiosqlite\core.py", line 129, in _execute
    return await future
  File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\aiosqlite\core.py", line 102, in run
    result = function()
sqlite3.OperationalError: database is locked

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\client.py", line 502, in _run_event
    await coro(*args, **kwargs)
  File "c:\Users\PC\Desktop\Aleccy Bot\main.py", line 608, in on_command_error
    raise error
  File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\ext\commands\bot.py", line 1382, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\ext\commands\core.py", line 948, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\ext\commands\core.py", line 174, in wrapped
    raise CommandInvokeError(exc) from exc
nextcord.ext.commands.errors.CommandInvokeError: Command raised an exception: OperationalError: database is locked
cloud dawn
slate swan
cloud dawn
#

CTRL+SHIFT+ESC

slate swan
#

opens that

#

oh nvm did it wrong

#

ill check

#

wait what

#

it opens window

cloud dawn
#

Called task manager.

#

Look if your bot is running twice.

#

Or more..

slate swan
#

okay

cloud dawn
#

Bottom right/

slate swan
#

םל

#

ok

#

what now

cloud dawn
#

Check vscode or python if it is running twice or more.

slate swan
#

Okay

#

holy shit

#

@cloud dawn i reset my token and now it works perfectly, did someone got my token?

cloud dawn
#

No you just destroyed the other windows because you did that.

#

You were just running bot twice or more on your machine.

slate swan
#

oh

#

tysmmm!

nimble timber
#

nickolay@macbook-pro-mikola discordbot % py -3 main.py
zsh: command not found: py
nickolay@macbook-pro-mikola discordbot % py3 -3 main.py
zsh: command not found: py3

#

does anyone know how to make the py command work?

shrewd apex
shrewd apex
lucid latch
#

RuntimeWarning: coroutine 'music' was never awaited
self.after(error)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback

#
voice.play(discord.FFmpegPCMAudio(source = URL, ** FFMPEG_OPTIONS), after=lambda e: music(ctx))```
#

what's the matter?

naive briar
#

You need to await the coroutine

quaint epoch
#

You can't have async lambdas

#

You need to create a separate func

vale wing
#

After doesn't accept coros anyway

slate swan
#

crazy

#
async def unbanid(a: discord.Interaction, user: int)
#

why does int make user ids not work

jovial lynx
glad cradle
#

bad indentation

slate swan
#
@miner.tree.command(name='unbanid', description='unbans an id from a server, bot must be in it')
@app_commands.describe(user = 'Put a userid!')
async def unbanid(a: discord.Interaction, user: str):
  username = a.guild.get_member(user)
  try:
    await a.guild.unban(user)
    await a.response.send_message(f"Unbanned {username}")
  except:
    if username == None:
      await a.response.send_message("No User Found")
    else:
      await a.response.send_message(f"Couldnt unban {username}")

why doesnt this work?

slate swan
#

?

#

??

slate swan
jovial lynx
#

how u get the colour thing?

slate swan
#

I dont rlly remember but u can check a tut

sick thicket
#

So pycord apparently has a View within which we can nest action rows, buttons, etc... is that a new component type from Discord or is it a pycord abstraction?

sick birch
#

When pycord forked discord.py the View class came with it

#

And it's an abstraction, discord doesn't have any sense of a "view" how we know it

sick thicket
#

ah

#

yeah I'm used to writing it out as nested action rows (?) from another language

#

so I was confused if it was an undocumented discord component type perhaps

slate swan
#

discord.py (and forks except disnake) don't use actionrows and have a View interface instead

#

Hello, I would like to authorize a command in a specific room by server using a sqlite database by doing for example n!commandallow #salon, could you help me ?

sick birch
sick birch
#

A view is composed of a maximum of 5 action rows

slate swan
#

internally ofcourse, there's no other way around to interact with the api lol
but you can't manually create a ActionRow as in the discord object

slate swan
sick thicket
#

as that's how it's passed to Discord API in the end

sick birch
#

Yes the discord API has an action row so a library must as well

slate swan
#

Hello, I would like to authorize a command in a specific room by server using a sqlite database by doing for example n!commandallow #salon, could you help me ? You can help me ?

#

Or with a .txt file

#

IS IT POSSIBLE TO ADD A WHILE LOOP IN THE ON READY EVENT

slate swan
#

like

#

@bot.event
async def on_ready():
global Channel
while True :
if len(Channel.members) == 0 :
await Channel.delete()

jaunty goblet
#

I need one on one help

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

okay

slate swan
slate swan
#

What do you mean, I don't understand ?

slate swan
jaunty goblet
#

where are those

#

ah i see

#

thx

slate swan
slate swan
#

do you have any code you made for that? @slate swan

slate swan
#

and then use @tasks.loop

slate swan
slate swan
# slate swan Not yet

hm so your first task would be creating a table in the sqlite db that establishes a relation between disabled command and channel/server id in columns

#

is #salon in your question meant to be a channel>

#

can this code work ?

slate swan
slate swan
#

this can work ?

devout iris
#

is there any slash command docs?

slate swan
# slate swan

the command has to enabled/disabled all bot commands or a specific one?

slate swan
devout iris
slate swan
#

I want to be able to perform this command in a room that we define with a command n!commandallow.

slate swan
slate swan
#

Yes one text channel for this command per server

#

yeah then you can just insert the server id and the channel id in the database table when command is used

next, make a check for that command which makes sure that the command was used in the desired channel

#
import os
import sqlite3

class Command_allow():
    def __init__(self, database_name : str):
        self.con = sqlite3.connect(f"{os.path.dirname(os.path.abspath(__file__))}/{database_name}")
        self.con.row_factory = sqlite3.Row

def command_allow_add(self, guild_id : int, channel : int):
    cursor = self.con.cursor()
    query = "INSERT INTO command_allow (guild_id, channel) VALUES (?, ?);"
    cursor.execute(query, (guild_id, channel))
    cursor.close()
    self.con.commit()
```I did this to save the information in the db
slate swan
fading marlin
#

I don't think you're supposed to have 1 always-open connection

slate swan
slate swan
unkempt canyonBOT
slate swan
#
@bot.command()
async def commandallow(ctx, channel : int):
    if (not ctx.author.guild_permissions.ban_members):
        await ctx.send(f"Vous n'avez pas l'autorisation {ctx.author.mention}")
        return
    command_allow.add_guild_id(ctx.guild.id, channel)
    await ctx.send("Channel defined")``` is good ?
#

for defined id

#
def command_allow_check(self, guild_id : int, channel : int):
    cursor = self.con.cursor()
    query = "SELECT channel FROM command_allow WHERE guild_id = ?;"
    cursor.execute(query, (guild_id, channel))
    result = list(map(dict, cursor.fetchall()))
    cursor.close()
    return result```
Is good @slate swan ?
#

you can actually do ```py
query = "SELECT channel FROM command_allow WHERE guild_id=? AND channel=?"
result = cursor.execute(query, (guild_id, channel)).fetchone()
return True if result else False

#

this will make the function return True if the channel is allowed , else false

#

Currently it does not register anything in the database

jaunty goblet
#

Does anyone know about xpaths?

fading marlin
slate swan
jaunty goblet
slate swan
#

change the data types to BIGINT maybe

slate swan
slate swan
#

BLOB ?

#

blob will save it as bytes or string

#

use BIGINT for longer integers

#

I d'ont have BIGINT

#

I test

slate swan
slate swan
#

the database might not have traced the changes because you closed the cursor with changes

slate swan
#

swap the last 2 lines of command_allow_add function

bright wedge
slate swan
bright wedge
slate swan
#

Nothing registers in the db

slate swan
#

I am having this issue doing pip install pycrypto

#

does nayone know the solution?

slate swan
bright wedge
mighty pilot
shadow vigil
#

hay can i note a user?

#

if so how?

orchid ledge
#

is there a way that the bot says automaticly thanks when someone boosts the server?

shadow vigil
orchid ledge
#

yeah me too but I dont get what they mean xd

#

still thinking haha

shadow vigil
#

there is no event for boosting

orchid ledge
#

thats kinda sad. But saw that already somewhere else

shadow vigil
#

there is way like answer number two or checking members after 10s and see if they're boosted the server

orchid ledge
#

thats alot ticks after a while :c

fading marlin
shadow vigil
fading marlin
fading marlin
orchid ledge
#

Will be the "on message" bc some ppl Boost twice yk 😄

#

so ill just do an privat channel and an open one where the bot sends the "thanks"

shadow vigil
orchid ledge
#
@bot.event
async def on_message(message):
    if message.type == discord.MessageType.premium_guild_subscription:
        print(str(message.author))```
#

do I just put an await under it?

slate swan
#

does anyone want to work on a discord bot with me

orchid ledge
sick birch
#

Good point

#

Can't test it

orchid ledge
#

xD

#

Wait... if someone boosts and I say "blabla thanks for the boost".... what do I need to do for Tagging? Author ? xD

slate swan
#

no

orchid ledge
slate swan
#

u do author.id to get the id and then wrap it with <@> so like @worldly epoch

sick birch
#

Try just doing print(message) and then boost

#

It should print everything about the boost and you can go from there

slate swan
#

does anyone want to work on a discord bot with me

orchid ledge
pliant gulch
# sick birch Can't test it
@bot.event
async def on_message(message: discord.Messge) -> None:
    message.type = discord.MessageType.premium_guild_subscription # patch
    
    if message.type == discord.MessageType.premium_guild_subscription:
        print(str(message.author))
```we do a little trolling
sick birch
#

As long as it's not inside the if statement

orchid ledge
#

@sick birch

#

so yes

#
@bot.event
async def on_message(message):
    if message.type == discord.MessageType.premium_guild_subscription:
        await message.channel.send("Thanks for the Server Boost ")
        print(message)```
#

thats what I got for now

sick birch
slate swan
#

does anyone want to work on a discord bot with me

sick birch
slate swan
#

ok :(

orchid ledge
#

it works! Lets go thank you Robin kiss

#

okay last question... how do I tag them ? I mean "message.author" works lmao PepeLaugh

sick birch
#

message.author.mention

orchid ledge
#

ty!

#

oh nvm... "channel=bot.get_channel()" is right , right? 😄

shrewd pasture
orchid ledge
#

anyone got a nice GIF for Embed images??

#

Small Lines or smth

shrewd pasture
orchid ledge
shrewd pasture
#

theres 3

shrewd pasture
#

ohh i see

orchid ledge
#

like that yk ?

bright wedge
#

what we are trying to do?

#

give me issues

orchid ledge
#
@bot.event
async def on_message(message):
    if message.type == discord.MessageType.premium_guild_subscription:
        channel=bot.get_channel(1043836095374303242)
        embed=discord.Embed(title=":wave: Danke für den Serverboost!", description=f"Danke für den Serverboost! {message.author.mention}!)
        embed.add_field(name="**Nicht vergessen!**", value="Vergiss nicht deine Vorteile abzuholen!")
        embed.set_image(url="https://cdn.discordapp.com/attachments/1035876269394493490/1044436064753950800/ligne-gif-discord-line.gif")
        await channel.send(embed=embed)
        print(message)```
bright wedge
orchid ledge
#

here, is this working? I mean it was working before, but in the channel where the server sends the boost message, I want it in another channel

orchid ledge
#

oh got it haha

bright wedge
#
@bot.event
async def on_message(message):
    if message.type == discord.MessageType.premium_guild_subscription:
        channel=bot.get_channel(1043836095374303242)
        embed=discord.Embed(title=":wave: Danke für den Serverboost!", description=f"Danke für den Serverboost! {message.author.mention}!")
        embed.add_field(name="**Nicht vergessen!**", value="Vergiss nicht deine Vorteile abzuholen!")
        embed.set_image(url="https://cdn.discordapp.com/attachments/1035876269394493490/1044436064753950800/ligne-gif-discord-line.gif")
        await channel.send(embed=embed)
        print(message)
orchid ledge
#

but this should work right? and should get send in the channel I put in right? pepeshy

#

worked like that, but wrong channel haha

#

theres no event for server boosts 🙂

bright wedge
#

what are you trying to do?

bright wedge
#

get the announcement channel of boosts?

orchid ledge
orchid ledge
#

what do I need to do if I want the "Status" to say how many discord members are in my guild?

#

example: "playing with ... 300 members"

upbeat gust
#

guild.members

orchid ledge
#

it was bot.users for me, but ty

slate swan
#

WARNING discord.gateway Shard ID None heartbeat blocked for more than 10 seconds.

#

What’s this

sick birch
slate swan
sick birch
slate swan
#

should I make them all async?

#

@sick birch

sick birch
#

Can you send your code that isn't async?

slate swan
# sick birch Can you send your code that isn't async?
def store_api(user_id, api_token):
    user_data = {user_id: api_token}
    try:
        with open(json_file, 'r') as file:
            temp = json.load(file)
        with open(json_file, 'w') as f:
            temp.update(user_data)
            json.dump(temp, f)
    except json.decoder.JSONDecodeError:
        with open(json_file, 'w') as f:
            json.dump({}, f)
        store_api(user_id, api_token)


def get_api(user_id):
    with open('userdata.json', 'r') as file:
        content = json.load(file)
        if user_id in content:
            api_key = content[str(user_id)]
            return api_key
        else:
            return "Error"
sick birch
#

Is that all of it?

#

That shouldn't block for 10 seconds

slate swan
#
def create_catchall(catchall):
    firstname = names.get_first_name()
    lastname = names.get_last_name()
    two = ''.join(random.choice(string.digits) for _ in range(2))
    email = f"{firstname}{lastname}{two}@{catchall}"

    return email
sick birch
#

It's CPU bound

slate swan
#

AH I see im sending a request

#

but idk if the api im sending the request to is within the servers terms so I will pass

sick birch
#

Well that's where the error probably is

#

You'll have to figure it out on your own

slate swan
#

yeah fair enough lol

sick birch
#

If you're not sure it's within this server's rules it's probably not

slate swan
#

every command of my bot doesnt work

sick birch
slate swan
#

lets say its a request to get the time in another city...

slate swan
sick birch
#

Do you have process_commands?

slate swan
#

no

sick birch
#

!d discord.ext.commands.Bot.process_commands

unkempt canyonBOT
#

await process_commands(message, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

This function processes the commands that have been registered to the bot and other groups. Without this coroutine, none of the commands will be triggered.

By default, this coroutine is called inside the [`on_message()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_message "discord.on_message") event. If you choose to override the [`on_message()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_message "discord.on_message") event, then you should invoke this coroutine as well.

This is built using other low level tools, and is equivalent to a call to [`get_context()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.get_context "discord.ext.commands.Bot.get_context") followed by a call to [`invoke()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.invoke "discord.ext.commands.Bot.invoke").

This also checks if the message’s author is a bot and doesn’t call [`get_context()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.get_context "discord.ext.commands.Bot.get_context") or [`invoke()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.invoke "discord.ext.commands.Bot.invoke") if so.

Changed in version 2.0: `message` parameter is now positional-only.
sick birch
#

Add it

slate swan
#

oh tyy

#
@bot.event
async def on_message(message):
    Channel = bot.get_channel(1036256958094770218)
    if message.author.bot:
        return
    embed = nextcord.Embed(title=f"New suggestion!", description=f"__**User:**__ \n {message.author.mention} \n \n __**Suggestion:**__ \n{message.content}", timestamp=datetime.now() , color=0x4e80cf)
    embed.set_thumbnail(url=message.author.display_avatar.url)
    embed.set_footer(text=f" {message.author} | {message.author.guild.name}")
    if message.channel is not Channel:
        return
    moji=await Channel.send(embed=embed)
    await moji.add_reaction('✅')
    await moji.add_reaction('❌')
    await bot.process_commands(message)```
#

still doesnt work

sick birch
slate swan
#

yes

sick birch
#

Both in the developer dashboard and in the code?

slate swan
#

yes

sick birch
#

I would double check and be 100% sure because that's the only other issue it could be

slate swan
#

intents=nextcord.Intents.all()

sick birch
#

Are you using your commands in the channel with ID 1036256958094770218?

slate swan
#

nono

sick birch
slate swan
#

oh

#

okay tyy!

#

finally works

#

tysm

tranquil badge
#

I’m not sure how hard this is to answer without looking at the code. Not able to provide it atm.

Are hybrid commands able to work with sql database queries? Was getting a “data cannot be str, must be int” error. Tried some print tests to see where the problem is. Even commented it out to see if removing parts of it would work, just to get any response at all.

#

Tired using int() to convert it but that didn’t work either.

slate swan
#

can you show code?

slate swan
#

How to I set a REQUIRED arg so when a user does not add the arg I can send a message to do so?

cloud dawn
slate swan
cloud dawn
#

Do you have an error handler?

#

Most likely that you suppressed the error.

tranquil badge
#

Don’t have the computer the code is on with me currently

#

I’ll probably be here tomorrow troubleshooting

cloud dawn
tranquil badge
#

Yea was just wondering if how it was coded previously will still be able to function for hybrid commands without much rewriting

cloud dawn
exotic hawk
#

How do i start making bots?

slate swan
#

Is there a way to host your bot for free?

rugged shadow
naive briar
cloud dawn
cloud dawn
rugged shadow
exotic hawk
cloud dawn
cloud dawn
#

What do you want to make.

exotic hawk
cloud dawn
exotic hawk
#

its gonna use sticky translation

#

so like for example ;ss (sticky start) [language]

#

;sc (sticky cancel)

cloud dawn
#

Never heard of it.

upbeat gust
#

Then check out

exotic hawk
#

basically you start the command and it will translate everysingle one of the user that started the command to whatever language

exotic hawk
#

im not a complete newb

upbeat gust
#

I'm literally just being as detailed as possible

#

Not assuming

exotic hawk
#

you dont need to

upbeat gust
#

Cool

exotic hawk
#

anyway

#

@cloud dawn

upbeat gust
#

then look at things on the docs

exotic hawk
#

dude

#

i dont need your help

upbeat gust
#

I mean I've already given you a link

cloud dawn
#

Could you guys not? It's a public channel.

exotic hawk
#

exactly

cloud dawn
exotic hawk
#

so for example
me: ;ss swedish
bot: swedish selected (idk didnt really think about this part)
me: hey
bot: (my username):hej

exotic hawk
cloud dawn
exotic hawk
#

i think message will be fine for my first one

#

rome wasnt built in a day was it

upbeat gust
cloud dawn
upbeat gust
#

You'd add users who have started it to a db along with what language they want

#

use the on_message event to get the messages they send

upbeat gust
# exotic hawk exactly

Exactly what? I simply told you what you should know, and a guide to get you started. You decided to start getting aggressive

slate swan
#

still getting thisd error

upbeat gust
#

Try using py -m pip install pycryptodome

#

@slate swan

exotic hawk
upbeat gust
#

lol what has the other guy helped you with
Telling u it's doable

exotic hawk
#

just stop ong

lucid latch
#

RuntimeWarning: coroutine 'music' was never awaited
self.after(error)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback

voice.play(discord.FFmpegPCMAudio(source = URL, ** FFMPEG_OPTIONS), after=lambda e: music(ctx))```
what's the matter?
meager chasm
#

So u need to await it or schedule it with asyncio.create_task

#

U can also use asyncio.run_coroutine_threadsafe since ig Discordpy uses threads for music playback

upbeat gust
#

It's completely different

meager chasm
#

and u can also read asyncio docs to learn how it wrks

lucid latch
#

ok thx!!

cloud dawn
#

They way you load cogs it's... it's..... ... ..

loud junco
#

lemme show u but i have a slight issue tho

cloud dawn
#

Is this cog test2?

loud junco
#

this is the output tho

#

this is the table

cloud dawn
#

Besides the list comp... loading it before starting up the bot is actually pretty good.

cloud dawn
#

But then again you have to setuphook for that as well.

loud junco
#

help me with the db.py ;-;

cloud dawn
#

asyncio.get_event_loop().run_until_complete(main()) I don't see a main so yeah that could be lol

cloud dawn
loud junco
#

ignore that

#

look at my new ones

loud junco
cloud dawn
#

I've looked

loud junco
#

👀

cloud dawn
#

Does it work?

loud junco
#

output

#

i think the error is the way i force take the value 💀

cloud dawn
#

Looks fine to me

loud junco
loud junco
cloud dawn
#

var[0]["matchplayer"] should do the trick.

loud junco
cloud dawn
cloud dawn
#

You always get a record object back.

#

Not the value.

loud junco
cloud dawn
#

How you get the value

loud junco
cloud dawn
#

Yes

loud junco
loud junco
cloud dawn
cloud dawn
#

Oh yeah that.

loud junco
#

💀

#

my man is meme-ing me

cloud dawn
#

await ctx.send(var[0]["matchplayer"])

loud junco
#

hmm ok

#

so var is a list?

cloud dawn
#

It always returns a list

#

Since why not.

loud junco
#

ok

#

why did sarth send me a so complicated version ;-;

cloud dawn
#

asyncpg is the best

loud junco
#

ye

cloud dawn
#

It's syntax is what wakes me up.

#

That says a lot since I sleep 18 to 20 hrs a day.

loud junco
#

'matchplayer'

#

best error of the year

upbeat gust
#

'error'

cloud dawn
#

Your logger is just having a stroke.

#

But my guess is that we need something else to get the value.

loud junco
#

how do i even make railway.app log error normally

#

💀

#

i literally need to log like this

upbeat gust
#

do you use bot.run?

loud junco
upbeat gust
#

Do you use it or not

loud junco
upbeat gust
#

bot.run(token)

loud junco
#

ok

cloud dawn
# loud junco this is my main.py
import asyncpg
import asyncio
loop = asyncio.get_event_loop()
conn = loop.run_until_complete(asyncpg.connect())
r = loop.run_until_complete(conn.fetchrow('''
    SELECT oid, rolname, rolsuper FROM pg_roles WHERE rolname = user'''))
r
<Record oid=16388 rolname='elvis' rolsuper=True>
r['oid']
16388
r[0]
16388
dict(r)
{'oid': 16388, 'rolname': 'elvis', 'rolsuper': True}
tuple(r)
(16388, 'elvis', True)
upbeat gust
cloud dawn
#

I was right.

loud junco
#

💀 what had i done

loud junco
#

what do i need to await

#

await asyncio.run? 💀

upbeat gust
#

just use utils.setup_logging

cloud dawn
loud junco
cloud dawn
#

No clue I've got my own logging.

upbeat gust
upbeat gust
loud junco
upbeat gust
#

thats it

loud junco
upbeat gust
#

main

loud junco
#

ok

#

is this healthy

upbeat gust
#

yes

loud junco
#

ok

loud junco
#

no error at all

#

not even 'matchplayer'

#

do i need parameter like the docs tho

upbeat gust
#

what parameter? leaving it like that is fine

loud junco
#

its only outputting 1

upbeat gust
upbeat gust
loud junco
upbeat gust
#

what are you expecting?

loud junco
#

its supposed to output
1
value from database
2

#

but it only outputted 1

#

alr the error is coming

#

what is this 🥹 @cloud dawn

silk robin
#

how come its saying this?

slate swan
#

most prob indention error, because there is no uunicode character as i see

slate swan
silk robin
#

this is unicode

upbeat gust
silk robin
#

what do i need to add for it to be able to read / print the unicode

slate swan
# silk robin

ahh then just to ignore this error use try and except statement

silk robin
#

? why would i ignore the error lol

slate swan
loud junco
#

-> best

silk robin
#

thats ugly tho lol

upbeat gust
# silk robin

I think you need to specify the encoding at the top of the file

loud junco
upbeat gust
#

or you could just fix the problem

slate swan
shrewd apex
shrewd apex
slate swan
shrewd apex
#

just var[0] is enough...

slate swan
#

is he or she even using sql db? 💀

shrewd apex
#

asyncpg postgres read the code

slate swan
#

oh, my bad

shrewd apex
# loud junco

also bruh u are returning before closing the connection why would u want to close the connection in first place just make the conn as an attr of bot instance and use it throughout

upbeat otter
upbeat otter
#

yep, that too

slate swan
#

attrs better aaaa_stress

shrewd apex
#

kinda equalising in 3.10

slate swan
#

!d attr there's one inbuilt too

unkempt canyonBOT
slate swan
#

oo nvm this another one

jade tinsel
#

I need help. Idk why channel is None.

intents.guilds = True
channel = bot.get_channel(CHANNEL_ID)```
`AttributeError: 'NoneType' object has no attribute 'send'`
maiden fable
#

u r getting from the cache before the bot is getting ready

jade tinsel
#

I tried several channel ids

slate swan
tranquil badge
#

I love seeing messages of people getting pissy when help is offered. “i KnOw hOw” but then “help with everything please? SCpray

bitter crag
#

what is the shortcut for rerun in terminal

quaint scaffold
bitter crag
#

okay

#

alr

glass quail
#

Do you guys know of decent guides to creating discord bots?

glass quail
shadow vigil
glass quail
shadow vigil
#

and contrab?

glass quail
#

Idk that is some I have heard but I have yet to use it.
By automate I mean, that as soon as the website gets updated with new anime anime news such as upcoming releases will be automatically announced by the discord-bot.
I am not sure if that process needs to updated. I thought beautifulsoup was good for static pages therefore if the page is updated with new information the bot would have to continuously scrape the page?
I am not too familiar tbh. Thank you for your patience

shadow vigil
maiden fable
#

Music bots are against ToS

shadow vigil
maiden fable
#

Yup

naive briar
#

It's against YouTube's ToS

maiden fable
#

They have been but Discord started enforcing those after the Groovy-YouTube lawsuit

shadow vigil
#

oh okay now that make sense

glass quail
#

Wait is there another way or source to get music from aside from YouTube?

maiden fable
#

There's Soundcloud iirc

shadow vigil
maiden fable
#

People say it allows streaming music but not sure

slate swan
#

SoundCloud and they are chilled as long as you ain't downloading and distributing it

maiden fable
#

There u go

#

Oh sarth

#

Nice, uhhhh name

slate swan
#

didn't get a single mention yet sadly

#

just shows how miserable the condition of app commands is 😔

glass quail
#

So is there a guide to creating a music bot using sound cloud?