#discord-bots

1 messages · Page 188 of 1

potent spear
#

right, that's a v2 thing, right?

naive briar
#

Like asyncio.Queue

potent spear
unkempt canyonBOT
#

examples/background_task.py lines 13 to 25

async def setup_hook(self) -> None:
    # start the task to run in the background
    self.my_background_task.start()

async def on_ready(self):
    print(f'Logged in as {self.user} (ID: {self.user.id})')
    print('------')

@tasks.loop(seconds=60)  # task runs every 60 seconds
async def my_background_task(self):
    channel = self.get_channel(1234567)  # channel ID goes here
    self.counter += 1
    await channel.send(self.counter)```
ionic garden
#

IT WORKS

#

THIS MADE IT WORK

potent spear
#

you changed...?

naive briar
#

They probably forgot to change the docs

potent spear
#

ah, loading cogs correctly ftw Ig

ionic garden
#

i just had t put the cog loading inside setup_hook

#

the template lied to me jesus

potent spear
#

they just do it in setup_hook because it's a startup / background task

potent spear
ionic garden
#

the other stuff? you mean the redundant on_message?

potent spear
#

that's one thing

#

.

ionic garden
#

.

potent spear
#

^ use your setup_hook more

#

no, do that in your setup_hook
you don't want a redundant if statement, doesn't matter if it gets triggered or not

naive briar
#

The example doesn't lie

potent spear
naive briar
#

Even trying to create new loop doesn't help, you need to run it in a async function đŸ€·

potent spear
#

ah, you just started outside the loop, I see

#

you're right most likely, stinky tasks

#

the question now is, where would you want to start a task when loading a cog?

naive briar
#

Good question

pliant gulch
potent spear
pliant gulch
#

You should make sure to unload in cog_unload otherwise you might get two running loops

#

And during active development that screams undefined behaviour too me

potent spear
#

you mean stop / cancel?

smoky sinew
#

@pliant gulch hello!

severe mural
#
        async def button2(self,interaction: discord.Interaction, Button: discord.ui.Button):
                await interaction.response.send_message("Sorry, not available working soon.", ephemeral=True) ``` problem error no solution URL button?
unkempt canyonBOT
#

examples/views/link.py lines 30 to 33

# Link buttons cannot be made with the decorator
# Therefore we have to manually create one.
# We add the quoted url to the button, and add the button to the view.
self.add_item(discord.ui.Button(label='Click Here', url=url))```
severe mural
#

@wicked atlas example look correct?

wicked atlas
#

put the second line you're pointing to inside your __init__ as well

wicked atlas
#

you've put a url variable there, but not the self.add_item(...) line

severe mural
#

hmm how is?

#

hmmm

wicked atlas
#

your __init__ ends here

severe mural
#

hmm maybe confuse lol: try code:

        def __init__(self):
            super().__init__(timeout=None)
            self.participants_count = 0
            url = 'https://www.google.com/search'

        @discord.ui.button(label="Participate", emoji="🎉", style=discord.ButtonStyle.primary)
        async def button(self, interaction: discord.Interaction, Button: discord.ui.Button):
            if interaction.user.id in participants:
                await interaction.response.send_message("You are already in the giveaway!", ephemeral=True)
            else:
                if participantRole2 != None:
                    if participantRole not in interaction.user.roles and participantRole2 not in interaction.user.roles:
                        await interaction.response.send_message("You dont have a role!", ephemeral=True)
                    else:
                        await self.adduser(interaction)
                elif participantRole not in interaction.user.roles:
                    await interaction.response.send_message("You dont have a role!", ephemeral=True)
                else:
                    await self.adduser(interaction)
                    
        self.add_item(discord.ui.Button(label='View Giveaway', url=url))
        #@discord.ui.button(label="View Giveaway", emoji="🔗", style=discord.ButtonStyle.secondary)        
        #async def button2(self,interaction: discord.Interaction, Button: discord.ui.Button):
             #   await interaction.response.send_message("Sorry, not available working soon.", ephemeral=True)  ```
#

try you code fix?

wicked atlas
severe mural
#

ah

#

done fix.

#

and?

wicked atlas
#

and what?

#

Did it work?

severe mural
#

button there last #@discord.ui.button(label="View Giveaway", emoji="🔗", style=discord.ButtonStyle.secondary) ....?

#

is ignore no?

wicked atlas
#

Yep, link buttons can't be created using the decorator, so you can remove that

severe mural
#

i see ok.

#

ok try on bot

#

@wicked atlas oh i see thanks

wicked atlas
#

👍

whole sparrow
#
   buttons_pressed = []
        view = View()
        
        counter = 1
        correct_answers = []
        
        async def call_1(interac):
            num = 1
            buttons_pressed.append(num)
            await interac.send(f"Selected answer: {num}")
            if len(buttons_pressed) == len(correct_answers):
                if buttons_pressed != correct_answers:
                    await interac.send(f"You haven't selected the correct answers! You can try again after 30 minutes.")
                    return
            print(buttons_pressed)
        async def call_2(interac):
            num = 2
            buttons_pressed.append(num)
            await interac.send(f"Selected answer: {num}")
            if len(buttons_pressed) == len(correct_answers):
                if buttons_pressed != correct_answers:
                    await interac.send(f"You haven't selected the correct answers! You can try again after 30 minutes.")
                    return
            print(buttons_pressed)
        async def call_3(interac):
            num = 3
            buttons_pressed.append(3)
            await interac.send(f"Selected answer: {num}")
            if len(buttons_pressed) == len(correct_answers):
                if buttons_pressed != correct_answers:
                    await interac.send(f"You haven't selected the correct answers! You can try again after 30 minutes.")
                    return


#

How do I make it so I can make 10 buttons to a message using a for loop but also add a callback to each button without creating 10 callback functions?

#

Perhaps within the for loop? Because when I do it just makes the function of the last iteration in the loop (e.g. 10th function)

hushed galleon
shrewd apex
#

i would just use the custom id ig

jaunty hare
#

why now it tolds me this, i already add ffmpeg to enviroment variables and the path is correct

hushed galleon
#

discord/discord-api-docs#3961

lament depotBOT
hushed galleon
#

presumably other flags they might have arent documented for a similar reason

hushed galleon
#

or you could add C:\ffmpeg\bin to your PATH environment variable and not have to configure executable= at all, which might be more ideal if you have (or will have) some other software that needs ffmpeg

jaunty hare
#

nah, i dont have other software that uses ffmpeg, but let me try

#

still giving me the same error

hushed galleon
#

which approach did you take? if its changing PATH, you'll need to restart your terminal/editor for your changes to apply

jaunty hare
#

oooh okay, let me restart

#

still the same error

#

okay, let me share the tutorial i follow to install ffmpeg

waxen igloo
#

how can i make errors log into a channel instead of console

hushed galleon
hushed galleon
jaunty hare
waxen igloo
#

by errors i dont mean any specific error but instead anything that is logged into the console

hushed galleon
jaunty hare
#

even the path?

hushed galleon
hushed galleon
# jaunty hare even the path?

changing executable="..." to "..." is not removing the argument, you're merely changing it from a keyword argument to a positional argument, hence why the syntax error appeared

#

speaking of which that argument is almost certainly interfering with it since \f and \b are being recognized as escape sequences

jaunty hare
#

soo, how i should write it?

hushed galleon
#

either dont write it at all, or fix it so your file path isnt messed up by the escape sequence detection ```py

Let discord.py find ffmpeg in PATH

discord.FFmpegPCMAudio("my_audio.mp3")

...or escape each backslash so they're treated literally

discord.FFmpegPCMAudio("my_audio.mp3", executable="C:\ffmpeg\bin\ffmpeg.exe")

...or prefix the string with "r" to make it ignore escape sequences

discord.FFmpegPCMAudio("my_audio.mp3", executable=r"C:\ffmpeg\bin\ffmpeg.exe")

...or use forward slashes which are supported on windows

discord.FFmpegPCMAudio("my_audio.mp3", executable="C:/ffmpeg/bin/ffmpeg.exe")```

jaunty hare
#

alright, let me try bro

jaunty hare
#

cuz NO ONE of the options work

#

let me reinstall vscode

jaunty hare
#

vscode should be here no?

#

@hushed galleon BRO with pycharm doesnt give me the error

slate swan
#

why i do config.config it shows me error line

naive briar
#

What error line

meager chasm
slate swan
#

ohh

slate swan
meager chasm
#

U can click on Problems tab and it will tell you

slate swan
#

it doesnt have any quick fix

meager chasm
#

Yea because you need to add init.py in config dir to mark is as package

slate swan
#

ohhh thank you so muchh

#

i forgot about init file

pulsar kettle
#

Working on a message delete log and I tried to make it so it detects deleted images too. It work when there's:
text no image, text 1 image and image no text but whenever I have text and 2 images or no text 2 images it always either replaces the text with a duplicate image or duplicates an image regardless. Any thoughts?

@bot.event
async def on_message_delete(message):
    if message.author.bot:
        return
    embed = discord.Embed(description = f"**A message sent by {message.author.mention} has been deleted in <#{message.channel.id}>**\n{message.content}", color = 0xf6ff00, timestamp = discord.utils.utcnow())
    if message.attachments:
        if len(message.attachments) == 1:
            if message.attachments[0].url.endswith(('.jpg', '.png', '.jpeg', '.gif')):
                embed.set_image(url = message.attachments[0].url.replace('cdn.discordapp.com', 'media.discordapp.net'))
            else:
                embed.add_field(name="Attachment", value = message.attachments[0].url)
        else:
            for attachment in message.attachments:
                embed = discord.Embed(description = f"**A message sent by {message.author.mention} has been deleted in <#{message.channel.id}>**", color = 0xf6ff00, timestamp = discord.utils.utcnow())
                embed.set_image(url = attachment)
                channel = bot.get_channel(1067413418597953637)
                await channel.send(embed=embed)
    embed.set_author(name = f"{message.author.name}#{message.author.discriminator}", icon_url = message.author.avatar)
    embed.set_footer(text = f"User ID: {message.author.id} ‱ Message ID: {message.id}")
    channel = bot.get_channel(1067413418597953637)
    await channel.send(embed = embed)```
#

Also noticed the duplicate log has the user and message ID whilst the others do not

jaunty hare
#

Hi!, i got a question, how i should give to discord.FFmpegPCMAudio() the source?

#

i tried like this, but it tolds me this problem (the urlself.mp3 is in the same folder than my cog file)

fresh fern
#

How to add voting system in a discord bot like after every 12 hrs it sends a reminder

slate swan
#

why the else: is wrong indented

vocal snow
#

Because the channel.send is not inside the if statement

vocal snow
#

Or are you doing everything from scratch

fresh fern
#

no scratch only python

#

actually my bot is verified on top.gg

sacred marlin
#

hey I want to make my own bot from scratch

#

using python

terse coyote
naive briar
fresh fern
#

help meeee

slate swan
#

I started only 1 file with bot*

terse coyote
slate swan
#

that means we can't use it for now?

nimble plume
#

hi

#

how can i delete msg on_timeout

#

(view)

#

disnake

vale wing
vale wing
#
class YourView(disnake.ui.View):
    def __init__(self, inter: disnake.ApplicationCommandInteraction):
        super().__init__(timeout=180)
        self.inter = inter

    async def on_timeout(self):
        await self.inter.delete_original_response()```
nimble plume
vale wing
#

Ah yes I look like a spoonfeeder

vale wing
nimble plume
#

im using listenr

vale wing
#

If it is just a view attached to a message then use message instead of interaction

#

Same principle

nimble plume
#

sorry 👍 , and thanks

orchid bear
#

non discrod bot related but how can I fix this? im trying to make a discord bot

static holly
#

hi, why it dont work please?

import discord
from discord.ext import commands
import os
from dotenv import load_dotenv

intents = discord.Intents.all()
bot = commands.Bot (command_prefix="!", intents=intents)


class automsg(commands.Cog):
    def __init__(self, bot):
        self.bot=bot


    @commands.Cog.listener()
    async def on_message(self, message):
        liste = ("Bonjour", "bonjour", "Bonsoir", "bonsoir")
        liste2 = ("Bonne soirée", "bonne soirée", "Bonne nuit", "bonne nuit")
        nombre_mention=len(message.mentions)

        for x in message.mentions:
            if (x==bot.user):
                await message.channel.send (f"DĂ©solĂ©, je ne me parle pas Ă  moi mĂȘme...")
cunning pasture
cunning pasture
pulsar kettle
naive briar
#

Logging deleted messages

cunning pasture
#

yeah

#

I added one but someone said it was not good for tos

pulsar kettle
#

I figured tons of bots have them so i assumed it was okay, is that incorrect?

cunning pasture
#

tons of bots also have/had music until discord said yeet ¯_(ツ)_/¯

vale wing
#

You need to read ToS by yourself or ask discord support

#

Actually they don't give a frick until somebody reports but that's not gonna happen cause nobody reads ToS

cunning pasture
cunning pasture
pulsar kettle
#

I heard about that

cunning pasture
cunning pasture
#

I still have music on my bot because some other people do and IDK if its actually not allowed or not

vale wing
#

If you're downloading it from youtube it is not allowed

cunning pasture
#

or maybe not, I don't think it matters if it's not monetized

vale wing
#

Spotify doesn't have API afaik

cunning pasture
#

or stream them to a vc

static holly
cunning pasture
#

also AFIAK they do

vale wing
#

Discord is getting rid of music bots with those activities

cunning pasture
vale wing
cunning pasture
#

Spotify URIs and IDs
In requests to the Web API and responses from it, you will frequently encounter the following parameters:

PARAMETER DESCRIPTION EXAMPLE
Spotify URI The resource identifier that you can enter, for example, in the Spotify Desktop client’s search box to locate an artist, album, or track. To find a Spotify URI simply right-click (on Windows) or Ctrl-Click (on a Mac) on the artist’s or album’s or track’s name. spotify:track:6rqhFgbbKwnb9MLmUQDhG6
Spotify ID The base-62 identifier that you can find at the end of the Spotify URI (see above) for an artist, track, album, playlist, etc. Unlike a Spotify URI, a Spotify ID does not clearly identify the type of resource; that information is provided elsewhere in the call. 6rqhFgbbKwnb9MLmUQDhG6
Spotify category ID The unique string identifying the Spotify category. party
Spotify user ID The unique string identifying the Spotify user that you can find at the end of the Spotify URI for the user. The ID of the current user can be obtained via the Web API endpoint. wizzler
Spotify URL An HTML link that opens a track, album, app, playlist or other Spotify resource in a Spotify client (which client is determined by the user’s device and account settings at play.spotify.com. http://open.spotify.com/track/6rqhFgbbKwnb9MLmUQDhG6

vale wing
#

Well seems like only metadata

cunning pasture
#

You can still download songs from spotify the other way :p

#

XD

cunning pasture
#

Or like probably

not message.author == self.user:

If it's in a cog

static holly
#

with else reply with "blablabla"?

cunning pasture
#

?

static holly
cunning pasture
static holly
#

yes

static holly
#

dont work, i tried it...

cunning pasture
#

tried what?

static holly
#

user.mentionned_in(message)

slate swan
cunning pasture
slate swan
cunning pasture
#

it would be whatever_ur_user_is.mentioned_in

slate swan
#

or even if someone replied to the bot

static holly
#
if bot.mentionned_in(message)
  await message.channel.send (f"DĂ©solĂ©, je ne me parle pas Ă  moi mĂȘme...")
#

it dont work

cunning pasture
#

nono

#

sec

slate swan
#

!d discord.Client.user

unkempt canyonBOT
slate swan
#

!d discord.ClientUser.mentioned_in

unkempt canyonBOT
flat pier
#

also that ^

static holly
#

no?

slate swan
#

read.

static holly
#

i dont understand the doc... 😕

cunning pasture
flat pier
#

you just read it.. what? you can clearly see Client.user, if Bot is a subclass of Client what else could it possibly be

slate swan
cunning pasture
slate swan
cunning pasture
#

bc you need class discord.abc.User

cunning pasture
shrewd fjord
#

🗿

shrewd fjord
#

Sarth

slate swan
#

spookie

shrewd fjord
#

cookie

cunning pasture
#

there's like 4 ways to do this

shrewd fjord
#

🗿

#

!d discord.ext.commands.when_mentioned_or

unkempt canyonBOT
#

discord.ext.commands.when_mentioned_or(*prefixes)```
A callable that implements when mentioned or other prefixes provided.

These are meant to be passed into the [`Bot.command_prefix`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.command_prefix "discord.ext.commands.Bot.command_prefix") attribute.

Example

```py
bot = commands.Bot(command_prefix=commands.when_mentioned_or('!'))
```...
shrewd fjord
#

Cool

slate swan
#

thats for the prefix specifically

shrewd fjord
#

Idk what he is trying

slate swan
#

not for checking if the bot was mentioned in message

shrewd fjord
#

So.... PU_PeepoLeaveExit

cunning pasture
slate swan
cunning pasture
#

there is several ways to answer this question

shrewd fjord
slate swan
#

yeps

shrewd fjord
slate swan
#

atleast from the current context

static holly
#

@cunning pasture i tried it and work fine

class automsg(commands.Cog):
    def __init__(self, bot):
        self.bot=bot


    @commands.Cog.listener()
    async def on_message(self, message):
        liste = ("Bonjour", "bonjour", "Bonsoir", "bonsoir")
        liste2 = ("Bonne soirée", "bonne soirée", "Bonne nuit", "bonne nuit")
        nombre_mention=len(message.mentions)

        if(self.bot.user in message.mentions):
            await message.channel.send (f"DĂ©solĂ©, je ne me parle pas Ă  moi mĂȘme...")
            return
#

i use "return" because i use other condition at the bottom of code

#

thanks all

cunning pasture
#

The primary reason behind YouTube taking down these music bots is that both bots offer a premium subscription that offers a tad bit of extra features on Discord. As Google confirmed to The Verge, Google took down Groovy as it violated its Terms of Service, including modifying the service to use it for commercial purposes.

#

¯_(ツ)_/¯

slate swan
#

youtube doesnt support any kind of automations in general, it's against their ToS

#
- access the Service using any automated means (such as robots, botnets or scrapers) except: (a) in the case of public search engines, in accordance with YouTube’s robots.txt file; (b) with YouTube’s prior written permission; or (c) as permitted by applicable law;
- collect or use any information that might identify a person (for example, harvesting usernames or faces), unless permitted by that person or allowed under section 3 above;
- use the Service to distribute unsolicited promotional or commercial content or other unwanted or mass solicitations (spam);
pulsar kettle
#

What do discord.py cogs do exactly? I've only ever heard partial bits of info on them

naive briar
#

Make your code more organized and cleaner

pulsar kettle
#

Yeah i should definitely look into them then since I have 688 lines on one .py file 💀

gusty pagoda
#

Im looking to make a Discord bot that displays Embeds, that i can put information in (For announcement/rules display purposes)

Does anybody have a good template? Im finding it hard to find.

if you do feel free to send me a friend request or tag me 🙂 thanks

jaunty hare
#

Feel free to dm me bro

cloud dawn
#

Anyone want to make a discord bot for me?

maiden fable
#

How many lemons am I getting?

cloud dawn
#

At least 0.5

maiden fable
#

Too less ;~;

#

What about 0.5*10?

cloud dawn
#

You strike a hard bargain I see.

#

0.5*5

maiden fable
#

1*3

cloud dawn
#

0.7*4

maiden fable
#

0.725*4?

cloud dawn
#

Deal

maiden fable
#

Yay

#

Wait, do I have to code the actual bot?

cloud dawn
#

Uhh

maiden fable
#

I have an idea
Gimme 0.7*4 lemons and u can code the bot yourself

cloud dawn
#

Ok but you code the base

maiden fable
#

Okay deal

sick birch
#

Tf going on here

maiden fable
cloud dawn
#

Convincing Hunter to get better at coding.

sick birch
#

My ass
Get back to work

maiden fable
#

Okay seriously @cloud dawn what bot u coding nowadays?

cloud dawn
#

No Discord bots lol, I've pretty much made everything.

#

I'm coding for my internship still

maiden fable
#

Oh nice
Best of luck!

cloud dawn
#

FastAPI + Alembic with React, TS + Chakra

slate swan
cloud dawn
#

Does it have a Client with slash commands that has extensions?

#

My way of doing it is still.. .interesting to say the least.

slate swan
maiden fable
slate swan
#

we can have bamboo trees instead of command trees in our wrapper

cloud dawn
#

I can see myself forking hikari just to rename everything.

maiden fable
#

Or create a panda plugin

cloud dawn
#

Will be a pain to code the updates tough.

slate swan
#

discord.ext.panda

cloud dawn
#

I don't credit myself in code, but I sure as hell do code with panda's in mind.

slate swan
#

now i want to make a dpy extension with alternative app commands style

cloud dawn
#

Once I got 30+ years of experience, finally, I can create the ultimate Discord bot.

fresh fern
#

help how can i use mongodb on replit

#

im hosting my bot on replit

cloud dawn
slate swan
#

!pip motor

unkempt canyonBOT
slate swan
#

use the python driver and use it to connect to your url

cloud dawn
slate swan
#

right right

fresh fern
#

can anyone tell me step by step

cloud dawn
#

I'm guessing he got a local host rn.

fresh fern
#

or a video

slate swan
fresh fern
fresh fern
#

didnt work

#

whats this motor thingy

cloud dawn
# fresh fern and u r right

Okay so you need to buy a host since otherwise you can better run the bot on your own pc. But it defeats the purpose of repl.it. Long story short, you can't use mongoDB without paying.

slate swan
cloud dawn
#

You simply can't.

fresh fern
#

idk i just didnt work

slate swan
cloud dawn
#

Just use a VPS and a docker compose.

fresh fern
#

there was no error on replit
but on pycharm it was working

cloud dawn
elfin cloud
#

i was ab to say

#

just buy a vps for like $5 with 4gb

#

u can easily run a proper bot on there

elfin cloud
cloud dawn
#

4gb pff then you can run like 16 bots

elfin cloud
#

thats what im saying

fresh fern
#

@slate swan

elfin cloud
#

i always get 8gb because ive got more things on it too

#

but 4gb is MORE then enough

cloud dawn
#

Minecraft server on the side.

elfin cloud
tough lance
#

hllo

cloud dawn
#

Been playing some astroneer too.

wraith meteor
#

Anyone have some example of function run on nextcord using Context.invoke?

cloud dawn
tough lance
#

@maiden fable yo still remember me :D

cloud dawn
#

Either using Bot or the Context object then you need to get the right command. Using Bot.commands you can geta a list of commands, using nextcord.utils.find you can find it using the syntax as stated here -> ```py
member = nextcord.utils.find(lambda m: m.name == 'Mighty', channel.guild.members)

wraith meteor
#

hm i need to run function (nextcord bot) from python not from discord or the bot itsolf

maiden fable
cloud dawn
maiden fable
#

My username goes brrrr

cloud dawn
#

That's not zalgo

wraith meteor
#

how say HI to discord form python:)?

cloud dawn
#

H̟̎͐u̶̜͒n̞̓͌t̷͐̏e̎̐̄r̶̐̀ ̎̐̈|Ì·ÌŸÌ” Ì”Ì†Í—á•‚ÌžÍ˜ÌŸá˜ÌžÌœÌá—ąÌ¶Í‹Ì’ Zalgo go yeet

maiden fable
#

Wait I don't remembered it being zalgo or smth
Wasn't it a simple English lettered name?

tough lance
#

A random Person

wraith meteor
#

i mean to run bot the function, not member dialog:)

maiden fable
cloud dawn
#

I don't get it

white citrus
#

How can i edit the embed before i sending it

hushed galleon
#

with attribute assignments and method calls...? that's the only way to modify a discord.Embed object

#

if you mean like editing an embed on an existing message, you just take the embed and change it, although it might be a safer idea to create a copy of that embed beforehand py embed = message.embeds[0].copy() embed.title = "New title" await message.edit(embed=embed)

wispy solstice
#

Does discord py support slash commands now ?

sick birch
wispy solstice
#

Simple code to see

sick birch
#

Here's an example

wispy solstice
#

Thanks

slate swan
#

i have this code ```py
import discord
from discord.ext import commands
import aiohttp
from bs4 import BeautifulSoup

headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:79.0) Gecko/20100101 Firefox/79.0'
}

client = commands.Bot(command_prefix="!", intents=discord.Intents.all())

@client.command()
async def celebrity(ctx, name):
name = name.replace(' ', '_')
url = f"https://fr.m.wikipedia.org/wiki/{name}"
await ctx.send(f"URL : {url}")
async with aiohttp.ClientSession() as session:
async with session.get(url) as response:
await ctx.send(response)
if response.status == 200:
soup = BeautifulSoup(await response.text(), "html.parser")
images = soup.find_all("img")
if images:
for image in images[:3]:
url = "https:" + image["src"]
async with session.get(url) as r:
if r.status == 200:
await ctx.send(file=discord.File(await r.read()))
else:
await ctx.send("Aucune image trouvée.")
else:
await ctx.send("Une erreur est survenue.")

client.run(token)```

#

but I receive an answer in the form of text encoded in UTF-8 while I requested images

fading marlin
#

You're sending the response, which sends that huge text

await ctx.send(response)
#

Also, surely Wikipedia has an API?

slate swan
#

yes they have but ill change the link to WikiFeet after

#

WikiFeet don't have api

slate swan
#

but u can see i have a awaiy ctx.send(file=discord.File(await r.read()))

fading marlin
#

Have you tried sending the URL instead?

slate swan
fading marlin
#

No, url = "https:" + image["src"] this url

slate swan
#

im not sure i cant get the images because theres in not the option 'save the img as'

golden edge
slate swan
#

where is ur bot = commands.Bot() ?

golden edge
#

omg

#

im so dumb

#

thank you i deleted on accident

#

fuck

#

now intents is broken

cloud dawn
#

You better not be using time.sleep

#

Violation

golden edge
#
  File "main.py", line 7, in <module>
    bot = commands.Bot(command_prefix='.', Intents=discord.Intents.all())
TypeError: __init__() missing 1 required keyword-only argument: 'intents'```
cloud dawn
#

Well what's there to say?

golden edge
#

i have all intents enabled

cloud dawn
#

Intents -> TypeError: __init__() missing 1 required keyword-only argument: 'intents'

golden edge
cloud dawn
#

No lmao

#

intents not Intents

#

Non capital i

golden edge
#

ahh

#

oml

#

thank you

raven kite
#

Hello, my Bot can't load cogs,
that's the script;

async def load():
    for filename in os.listdir(r'./cogs'):
        if filename.endswith('.py'):
            await bot.load_extension(f'cogs.{filename[:-3]}')


async def main():
    await load()
    await bot.run(token)

asyncio.run(main())
unkempt canyonBOT
#

Hey @raven kite!

It looks like you tried to attach file type(s) that we do not allow (). We currently allow the following file types: .gif, .jpg, .jpeg, .mov, .mp4, .mpg, .png, .mp3, .wav, .ogg, .webm, .webp, .flac, .m4a, .csv, .json.

Feel free to ask in #community-meta if you think this is a mistake.

raven kite
#

TypeError: object NoneType can't be used in 'await' expression

whole sparrow
#

Hi! Im making a function that records user button presses in an embed, is there a way in my slash command to wait for when there is a return of True or False?

#

idk i was doing something like this

#
        ok = await asyncio.wait_for(funcs.verification(inter, 0), timeout=None)
        print(f"Value of ok: {ok}")
slate swan
#

if true and if false

slate swan
#

help?.

#

đŸ§đŸœ

bright wedge
#

Where did you define it

austere vale
#
      if message.author not in(guild.members) or self.bot not in(guild.members):  
        await message.author.send('Your message was not sent to the mods. Please double check and make sure both you and I are in that server.')
        return 
``` Can someone help me with this error please?
im trying to make an if statement to check if both a user and my bot are in a guild
```py
0|bot  | Ignoring exception in on_message
0|bot  | Traceback (most recent call last):
0|bot  |   File "/usr/local/lib/python3.8/dist-packages/nextcord/client.py", line 512, in _run_event
0|bot  |     await coro(*args, **kwargs)
0|bot  |   File "/home/Runa/bot/cogs/moderation.py", line 161, in on_message
0|bot  |     if message.author not in(guild.members) or self.bot not in(guild.members):
0|bot  | AttributeError: 'NoneType' object has no attribute 'members'
austere vale
#

ah thank you!

slate swan
austere vale
#
if guild.get_member(message.author.id) is None:  
```could someone please help me with this error? im trying to make an if statement to check if a user is in a guild
```py
0|bot  | Ignoring exception in on_message
0|bot  | Traceback (most recent call last):
0|bot  |   File "/usr/local/lib/python3.8/dist-packages/nextcord/client.py", line 512, in _run_event
0|bot  |     await coro(*args, **kwargs)
0|bot  |   File "/home/Runa/bot/cogs/moderation.py", line 162, in on_message
0|bot  |     if guild.get_member(message.author.id) is None:
0|bot  | AttributeError: 'NoneType' object has no attribute 'get_member'
bright wedge
#

Just use one.

bright wedge
#

message.author.guild.get_member

austere vale
# bright wedge Define the guild

guild is defined here guild=self.bot.get_guild(msg.content)

basically, someone is supposed to DM the bot a server id.
so I dm my bot a server id, which is stored in msg.content

slate swan
austere vale
#

yes, trying to make a mod mail basically

bright wedge
#

And enable intents!

austere vale
#

so its basically goes like:

User sends bot a message
Bot: please give me the server ID you want to send this to
User: server.id
Bot: your message has been sent!

bright wedge
#

msg.content is string

#

Do int(msg.content)

#

And check

austere vale
#
  @commands.Cog.listener()
  async def on_message(self,message):
    if message.guild is None and message.author.bot is False:
      await message.author.send('Please provide the Server ID of the server you want to send the message to. For example: 702824491667161160')
      try:
        msg = await self.bot.wait_for('message', timeout=15.0)
      except asyncio.TimeoutError:
        await message.author.send('You didn\'t answer in time, please be quicker next time!')
        return
      #if the member or bot are not in the mentioned server 
      guild=self.bot.get_guild(int(msg.content))
      if message.author.guild.get_member is None:  
        await message.author.send('Your message was not sent to the mods. Please double check and make sure both you and I are in that server.')
        return 
0|bot  | Ignoring exception in on_message
0|bot  | Traceback (most recent call last):
0|bot  |   File "/usr/local/lib/python3.8/dist-packages/nextcord/client.py", line 512, in _run_event
0|bot  |     await coro(*args, **kwargs)
0|bot  |   File "/home/Runa/bot/cogs/moderation.py", line 161, in on_message
0|bot  |     if message.author.guild.get_member is None:
0|bot  | AttributeError: 'User' object has no attribute 'guild'
bright wedge
#

if guild == discord.Guild

slate swan
austere vale
#

so should i put the if message.author.guild.get_member inside an if guild==discord.Guild?

bright wedge
#

You need to define if the message is on dms or guild channel

austere vale
#

how and where would i do that?

bright wedge
sick birch
#

discord.DMChannel is enough

bright wedge
#

Didn't know that

sick birch
#

🙂

slate swan
#

may someone please help

bright wedge
#

Lastest version.

austere vale
bright wedge
#

Waiting for what message? After user sends the guild id?

austere vale
#

yes msg is the one where the user sends the guild id

bright wedge
#

So what we are waiting for now

#

The message?

#

Or the guild id?

austere vale
#

the guild id

bright wedge
austere vale
#

thanks for the example! i changed my code to this

  @commands.Cog.listener()
  async def on_message(self,message):
    if message.guild is None and message.author.bot is False:
      await message.author.send('Please provide the Server ID of the server you want to send the message to. For example: 702824491667161160')
      def check(m: nextcord.Message):
        return m.author == message.author and m.guild is None and m.content.isdigit()
      try:
        msg = await self.bot.wait_for('message', timeout=15.0, check=check)
      except asyncio.TimeoutError:
        return await message.author.send('You didn\'t answer in time, please be quicker next time!')
      #if the member or Runa are not in the mentioned server 
      guild=self.bot.get_guild(int(msg.content))
      if guild==nextcord.guild() is False:
        return await message.author.send('You did not provide a server ID. Please resend your message and try again.')
      if message.author.guild.get_member is None:  
        return await message.author.send('Your message was not sent to the mods. Please double check and make sure both you and I are in that server.')
```now im getting this error. do you know what i should be fixing?
```py
0|bot  | Ignoring exception in on_message
0|bot  | Traceback (most recent call last):
0|bot  |   File "/usr/local/lib/python3.8/dist-packages/nextcord/client.py", line 512, in _run_event
0|bot  |     await coro(*args, **kwargs)
0|bot  |   File "/home/Runa/bot/cogs/moderation.py", line 162, in on_message
0|bot  |     if guild==nextcord.guild() is False:
0|bot  | TypeError: 'module' object is not callable
austere vale
#

oh capital G?

bright wedge
#

discord.Guild is object

#

Yes and remove brackets ()

#

but you already do this check

#

if message.guild is None

#

So just use else (if guild exists)

#

Oh nvm now I see what you did

austere vale
#

i think the issue is that every time i send the bot a message its just going to trigger the entire on_message event to run again. maybe i should try using buttons/embeds or something for mod mail

bright wedge
#

I can tell you how I would do it.

austere vale
#

sure!

bright wedge
#

You can use a select menu

#

And create a option for each guild

#

But maybe you need to work on it

slate swan
#

dm me if you know how to make embeds in self py

bright wedge
#

Because if the bot and user share many guilds (50+)

#

You will need another and faster way to define the guild.

#

You got me?

austere vale
#

ahh i see. thank you so much

bright wedge
#

If user and bot share many guilds.

#

But you can optimize it

austere vale
#

i'll look into it tomorrow, thank you for the suggestion

green jacinth
#

does anyone have know if its possible to fetch a number of results using a specific search in the search bar?

#

Like this

green jacinth
flat pier
flat pier
#

but you can use history to check through channel history

green jacinth
#

any alternatives do you think?

flat pier
#

let me find the docs for it rq

bright wedge
flat pier
#

!d discord.TextChannel.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...
green jacinth
#

Ok. because I wanted to make a counter of messages sent in a channel and it would take the amount of results and send it when a player runs a command

flat pier
flat pier
green jacinth
#

makes sense

flat pier
#

alternatively you could just track message counts yourself with an on_messsage (if all you're trying to do is count messages sent in channels) and then save that count for each channel to a database, but ofc you wont get the total channel count, only what your bot could see in the time its had access to the channel

exotic maple
#

Hey how do i get a user from their ID using discord API because the bot does not share any servers with that user

#

this is what i got so far but i got an error

bright wedge
#

The id will be the first in result

exotic maple
bright wedge
#

No I can't write code for you .

exotic maple
#

thx

waxen igloo
#

how to edit a voice channel name?

bright wedge
#

!d discord.Guild.get_channel

unkempt canyonBOT
#

get_channel(channel_id, /)```
Returns a channel with the given ID.

Note

This does *not* search for threads.

Changed in version 2.0: `channel_id` parameter is now positional-only.
green jacinth
#

how do i make it so the user can put in 2 options and depending on what they type on second option it sends a different thing with slash commands?

slate swan
#

how can i get my self to joina server using my own self bot

static holly
#

i have this :

    @commands.command()
    async def say(self, ctx, *, arg):
        await ctx.send(f"{arg}")
        await ctx.message.delete()

what is the condition to add to prevent the bot from talking to itself if I mention @bot in the !say command?

unkempt canyonBOT
#

5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.

slate swan
#

đŸ€“

sick birch
#

Excuse me?

slate swan
#

"excuse me" - đŸ€“ đŸ’»

sick birch
#

Quoting someone and putting a nerd emoji after it does not give your argument any credibility, FWIW

primal token
#

No more selfbotsjoeangryno

slate swan
#

what can i do with a self bot thinkmon

sick birch
#

You're also not getting help with that attitude, disregarding the fact that it's malicious

slate swan
sick birch
#

It's in violation of Discord's terms of service

slate swan
#

why

sick birch
#

Because there's not many legitimate reasons to be automating a user account

slate swan
#

there is

sick birch
#

I never said there wasn't.

#

90% of the time it's for malicious reasons

slate swan
#

what could the malicious reasons be

sick birch
#

Rationale nonwithstanding rules are rules

slate swan
#

i dot see what u could do tahts malicious

sick birch
#

Do you not? I see plenty. Spamming Discord channels, spam creating Discord channels, spamming user's DMs, mass solicitation, mass advertisements, spreading mass malware, among many other

#

It's all too easy to be flooding Discord with requests with a self bot

slate swan
#

u can do all that with bots so i dont see why making self bots not good

primal token
#

Then just use a bot

slate swan
#

no

slate swan
#

I don't think discord.py even allows you to connect with a token if the account isn't a bot user anymore.

pulsar kettle
#

Trying to implement cogs to no success, getting the error message ModuleNotFoundError: No module named 'cogs' when I run !load test. Any tips?

import discord
import os
import random
import humanize
from discord.ext import commands

intents = discord.Intents.all()
bot = commands.Bot(command_prefix = "!", intents = intents, status = discord.Status.online, activity = discord.Activity(type = discord.ActivityType.watching, name = "you sleep"))

@bot.command()
async def load(ctx, extension):
    await bot.load_extension(f"cogs.{extension}")

@bot.command()
async def unload(ctx, extension):
    await bot.unload_extension(f"cogs.{extension}")

@bot.command()
async def reload(ctx, extension):
    await bot.unload_extension(f"cogs.{extension}")
    await bot.load_extension(f"cogs.{extension}")

async def load_extensions():
    for filename in os.listdir("./cogs"):
        if filename.endswith(".py"):
            await bot.load_extension(f"cogs.{filename[:-3]}")```
```python
import discord
from discord.ext import commands

class test(commands.Cog):

    def __init__(self, bot):
        self.bot = bot

    
    @commands.commands()
    async def test(self, ctx):
        await ctx.send("Pong")

def setup(bot):
    bot.add_cog(test(bot))```
slate swan
#

i have self bot for my alt

mild bluff
#

How would I host a bot if not using something like replit

naive briar
#

VPS

sick birch
pulsar kettle
sick birch
#

Are you on VSCode?

pulsar kettle
#

Yep

sick birch
#

Can you send us a picture of the file structure on the left bar?

pulsar kettle
sick birch
#

That all?

pulsar kettle
#

Yeah

#

Wait do u need the

sick birch
#

Your main.py file should be outside the cogs folder

pulsar kettle
#

Outline and timeline tabs

sick birch
#

Nah

pulsar kettle
#

Extension 'cogs.test' raised an error: AttributeError: module 'discord.ext.commands' has no attribute 'commands' but now a folder called __pycache__ appeared in the cogs folder so I take it that's some progress

sick birch
#

Yeah that's supposed to happen

sick birch
pulsar kettle
#

Yeah just fixed it

#

Extension 'cogs.test' raised an error: TypeError: object NoneType can't be used in 'await' expression

sick birch
#

Should be

async def setup(...):
  await ...
#

setup() was made into an async function in discord.py v2

pulsar kettle
#

Running !load test gives white text RuntimeWarning: coroutine 'BotBase.add_cog' was never awaited bot.add_cog(test(bot)) RuntimeWarning: Enable tracemalloc to get the object allocation traceback
Then if I run !test I get: Command "test" is not found

bright wedge
#

as @sick birch said must be in setup() function

#

so should be:

async def setup(bot: commands.Bot):
    await bot.add_cog(test(bot))
pulsar kettle
#

Thats with await bot.add_cog(test(bot))

#

Idk why it says it was never awaited even tho it says

async def setup(bot):
    await bot.add_cog(test(bot))```
bright wedge
#

run this

naive briar
#

I don't see the await statement

pulsar kettle
#

Yeah its fixed now

#

Now its just giving me Forbidden: 403 Forbidden (error code: 50013): Missing Permissions

bright wedge
#

its obvious error

#

error code: 50013 means that you don't have permission to perform that action.

pulsar kettle
#

Okay apparently it needs admin perms to send text messages, sure. But yeah its working now, thanks guys <3

bright wedge
#

if you understand we are good!

pulsar kettle
#

👍

whole sparrow
#

How do I see when someone's an event host discord.py

naive briar
#

What

bright wedge
gusty flax
#

Like who created an event?

#

The get_scheduled_event method I think works for that.

gusty flax
#

^ ye u use that object to retrieve what is shown in those docs

orchid bear
#

help pls

orchid bear
# orchid bear help pls

code:

@bot.tree.command(name="new_enemy")
@app_commands.describe(enemy_name = "NAME")
async def new_enemy(interaction: discord.Interaction, enemy_name: str):
    embed = discord.Embed(
        title="Enemy name",
        description="the enemy name",
        colour = discord.Colour.blue()
    )
    channel = bot.get_channel(1069621174184722534)
    embed.add_field(name="name", value=enemy_name, inline=False)
    await interaction.response.send_message(f"{await channel.send(embed=embed)}")```
orchid bear
vocal snow
#

Why are you calling channel.send and then putting it in an fstring and passing that to send_message

orchid bear
orchid bear
#

logs

vocal snow
#

Why are you using send_message then?

orchid bear
vocal snow
#

But you don't want to send a message to the channel the command was used in right

orchid bear
#

yep

slate swan
#

Making a giveaway system and I got the reactions and embed working, it's just I don't know why my bot isnt editing the giveaway message and making a new message about who won the giveaway. Here is the code: ```@bot.command()
async def giveaway(ctx, name:str, winners:int, time:str):
# convert time, with my amazing maths!!!
if 'd' in time:
time = int(time.strip('d')) * 24 * 3600
elif 'h' in time:
time = int(time.strip('h')) * 3600
elif 's' in time:
time = int(time.strip('s'))
else:
await ctx.send("Invalid time format. Use 'd' for days, 'h' for hours and 's' for seconds.")
return
seconds = time

embed = discord.Embed(title=f"{name} Giveaway", description=f"{winners} winner(s) can win! Time left: {seconds} seconds.", color=0x00ff00)

message = await ctx.send(embed=embed)

await message.add_reaction('🎉')

await asyncio.sleep(time)

users = await message.reactions[0].users().flatten()


users.remove(bot.user)

winners_list = random.sample(users, winners)

winners_text = "\n".join([f"<@{user.id}>" for user in winners_list])
embed.add_field(name="Winners:", value=winners_text, inline=False)

await message.edit(embed=embed)

await ctx.send(f"And the winners of the {name} giveaway are... {winners_text}! Congratulations!")```
#

If anyone can help thank you.

shrewd fjord
slate swan
#

maybe I am unsure.

shrewd fjord
#

Try putting some small times like 5 secs or something

naive briar
#

users method returns an async generator in discord.py 2

slate swan
#

Anyone here who can help me get my discord bot hosted on aws

ionic garden
slate swan
#

i want 20ms

shrewd fjord
#

It's probably your internet problem, if u running the bot on your local system

slate swan
#

Mate...

#

I use pebblehost to host my bot and get 40ms ping

#

Apparently AWS has the fastest servers

rare echo
frail rock
#

can someone help me, not super familiar with discord bots on python, just learning. I know other programming languages though

my bot is connecting to the server and showing up as online but it won't respond to commands

import discord
import os #for token

#Connect to discord client
#This creates a connection instance.
client = discord.Client()

#registering an event
@client.event
#called when the bot is ready to be used
async def on_ready():
 print('We have logged in as {0.user}'.format(client))

@client.event
async def on_message(message):
#checking if the user came from the bot
if message.author == client.user:
  return
if message.content.startswith('$hello'):
send message to channel
 await message.channel.send('Hello!')

try:
 client.run(os.getenv("TOKEN"))
except discord.HTTPException as e:
 if e.status == 429:
      print("The Discord servers denied the connection for making too many requests")
    print("Get help from https://stackoverflow.com/questions/66724687/in-discord-py-how-to-solve-the-error-for-toomanyrequests")
  else:
     raise e

my_secret = os.environ['TOKEN']

client.run(my_secret)
pulsar bridge
#

Trying to save an attachment as a text file, then read the text file... but I'm getting a UnicodeDecode error. The file is all english, and all normal symbols.

Traceback (most recent call last):
  File "C:\Users\main\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\app_commands\commands.py", line 850, in _do_call
    return await self._callback(self.binding, interaction, **params)  # type: ignore
  File "C:\Users\main\Downloads\Personal Stuff\Bots\Fate of the System\bot.py", line 447, in locate
    f = await openedfile.read()
  File "C:\Users\main\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\aiofiles\threadpool\utils.py", line 45, in method
    return (yield from self._loop.run_in_executor(self._executor, cb))
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.2544.0_x64__qbz5n2kfra8p0\lib\concurrent\futures\thread.py", line 58, in run
    result = self.fn(*self.args, **self.kwargs)
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.2544.0_x64__qbz5n2kfra8p0\lib\encodings\cp1252.py", line 23, in decode
    return codecs.charmap_decode(input,self.errors,decoding_table)[0]
UnicodeDecodeError: 'charmap' codec can't decode byte 0x9d in position 733: character maps to <undefined>

The code:

await text.save(file_directory)
async with aif.open(file_directory, 'rt') as openedfile:
    f = await openedfile.read() # <- Error Line
pulsar bridge
frail rock
#

thanks

#

so like this?

#
@client.event
async def on_message(message):
  await bot.process_commands(message)
#checking if the user came from the bot
if message.author == client.user:
  return
if message.content.startswith('$hello'):
#send message to channel
 await message.channel.send('Hello!')
pulsar bridge
#

Should work

frail rock
#

other than forgetting to comment something out

pulsar bridge
#

Oh wait, you're putting bot there, put client

glad cradle
pulsar bridge
glad cradle
#

btw rt is the default mode

pulsar bridge
#

Yea, I have a habit of specifying anyway ^^;

frail rock
#

what the fuck is up with the indentation in this language OMG

pulsar bridge
#

The indentation is great imo
makes it look neat af

glad cradle
#

are you sure that the file doesn't contains unknown symbols for the text mode?

frail rock
#

I want to pull my hair out give me brackets

naive briar
#

Python is love, Python is life

frail rock
#

I come from languages with brackets. this is such a pain

naive briar
#

And use discord.ext.commands.Bot if you want to create prefix commands

frail rock
#

I pasted your code in nexus and its giving me an indentation error

glad cradle
# pulsar bridge Yup

The only thing I can think of is that the file is saved with the txt extension but actually it isn't a txt file

pulsar bridge
#
@client.event
async def on_message(message):

  await client.process_commands(message)

  #checking if the user came from the bot
  if message.author == client.user:
    return

  if message.content.startswith('$hello'):
  #send message to channel
   await message.channel.send('Hello!')

@frail rock, try this?

pulsar bridge
glad cradle
naive briar
#

There's no process_commands

frail rock
#

hold on, it worked. was just throwing an "indentation error"

#

Yeah still not responding though

pulsar bridge
glad cradle
#

shouldn't the process commands go at the end of the function?

pulsar bridge
frail rock
#

thats it doesn't respond

glad cradle
#

btw you're using discord.Client right?

frail rock
frail rock
glad cradle
#

then this won't work

frail rock
# glad cradle .

I don't know I just started using python for bots lmao. i do javascript normally.

#

how do I make it respond?

glad cradle
#

to get started you should use discord.ext.commands.Bot if you want prefix commands

naive briar
#

!d discord.ext.commands.Bot

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.
frail rock
#

think I will just go back to javascript

#

I thought python would be super simple for this

slate swan
#

Python is pretty simple imo

#

You can’t just dive in head first you need to understand what you’re writing

frail rock
#

yeah i am a comp sci student but I don't work with python regularily

naive briar
frail rock
#

I am familiar with many other languages just not python

#

I wanted to give it a go because I really like python but I don't have formal understanding of the syntax

slate swan
#

Then use one of the other languages you are familiar with lol

slate swan
frail rock
#

yeah I have watched like a video or two but I don't fully know how the library works

#

if there's like documentation that might help

frail rock
pulsar kettle
#

How do you use slash commands in cog files?

@commands.command()
    async def test(self, ctx):
        await ctx.send("Pong")```
naive briar
#

!d discord.app_commands.command

pulsar kettle
#

Is it the same an in regular?

unkempt canyonBOT
#

@discord.app_commands.command(*, name=..., description=..., nsfw=False, auto_locale_strings=True, extras=...)```
Creates an application command from a regular function.
pulsar kettle
#

So this? If so it's not working

@app_commands.command()
    async def hello(self, interaction: discord.Interaction):
        await interaction.response.send_message("Hello")```
#

Probably missing somethign aha

#

account made 1 day ago

pulsar kettle
#

Sorry should have sepcidfied, the slash command doesnt appear when i put /hello

naive briar
#

Did you sync

pulsar kettle
#

Smooth brain moment, how do you sync

#

Everytime i tried to check if updated commands work i just closed the terminal and reran the bot

naive briar
#

!d discord.app_commands.CommandTree.sync

unkempt canyonBOT
#

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

Syncs the application commands to Discord.

This also runs the translator to get the translated strings necessary for feeding back into Discord.

This must be called for the application commands to show up.
pulsar kettle
#

So like this in the cog file?

@commands.command()
    async def sync(self, ctx) -> None:
        await ctx.bot.tree.sync(guild = ctx.guild)
        await ctx.send("Successfully synced")
        print("Successfully synced")```
distant python
#

bot.http.__session is this not where the clientsession is

light violet
#
file = open('test.txt', "r")
  content = file.readlines()
  for line in content:
    text1, text2 = line.strip().split('×')
    if text2 =="test2":
       line.remove()```
#

how do i remove a line

#

i mean delete it

#

@distant python

distant python
#

yo

light violet
#

help me

#

.

distant python
#

bro what

#

text1, text2 isnt a list

light violet
distant python
#

ok good for you i dont know whats in ur text file

light violet
#

no error on that i just want to delte that line

distant python
#

what does this have to do w/ discord.py go to a normal help channel

light violet
#

1st line

light violet
#

if u know.......then help me pls

distant python
light violet
#

ok

distant python
#

therefore its not relevant to this channel

terse coyote
#

how to add persistent select menu? i have example https://github.com/Rapptz/discord.py/blob/master/examples/views/persistent.py
but example with buttons, and when i'm doing like in this example i have error

ValueError: View is not persistent. Items need to have a custom_id set and View must have no timeout```
GitHub

An API wrapper for Discord written in Python. Contribute to Rapptz/discord.py development by creating an account on GitHub.

naive briar
light violet
#

how do i simply make a cmd with 2 confirmation yes no buttons in side the cmd only and not in any class

cloud dawn
#

That will be one hefty command

light violet
#

pls help me

#

i need a simple one

shrewd fjord
#

!d discord.ui.Button

unkempt canyonBOT
#

class discord.ui.Button(*, style=<ButtonStyle.secondary: 2>, label=None, disabled=False, custom_id=None, url=None, emoji=None, row=None)```
Represents a UI button.

New in version 2.0.
shrewd fjord
#

U can create button using this

#

the button needs to be have a callback

#

!d discord.ui.View

unkempt canyonBOT
#

class discord.ui.View(*, timeout=180.0)```
Represents a UI view.

This object must be inherited to create a UI within Discord.

New in version 2.0.
white citrus
#

Hey there, can anyone help me?

naive briar
#

Just ask

light violet
#
@client.command()
async def gen(ctx,amt:int=None):
  button1 = Button(label="Confirm", style=discord.ButtonStyle.blurple, emoji=':blue_circle:')
    
  async def button1_callback(interaction):
    
    if interaction.user.id!=ctx.author.id:
      return
    else:
        
      await refresh(ctx)
  button1.callback = button1_callback
  button2 = Button(label="Cancel", style=discord.ButtonStyle.blurple, emoji=':blue_circle:')
    
  async def button2_callback(interaction):
    
    if interaction.user.id!=ctx.author.id:
      return
    else:
        
      break
  button2.callback = button2_callback
  view = View(timeout=60) 
  view.add_item(button1)
  view.add_item(button2) 
  await ctx.send("Initiating...Want Refresh?",view=view)```
naive briar
light violet
#

how do i wait for button click and then do rest of the function

light violet
naive briar
#

It not, the way you want to do it will just make it unreadable

#

And the way you have to create button instances, set the callback by setattr, adding to the view is way way longer

#

Just subclass the view

white citrus
#

If I run the command again, the embed is correct

cloud dawn
#

Is this Python?

tough lance
white citrus
tough fern
#
discord = OAuth2Session(client_id, token=session['discord_token'])
    me = discord.get(base_discord_api_url + '/users/@me')
    guild = discord.get(base_discord_api_url + '/users/@me/guilds')
    g = []
    for gs in guild.json():
        gMember = discord.get(base_discord_api_url + f'/users/@me/guilds/{gs["id"]}/member')
        g.append(gMember.json())
#discord API```
what i'm trying to do: getting member of a guild (by guild id => https://discord.com/developers/docs/resources/user#get-current-user-guild-member)
what i'm getting instead:


nvm just need a guilds.members.read scope
Discord Developer Portal

Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.

cloud dawn
tough fern
cloud dawn
#

Oh, well you know Hikari has an restAPI for this?

tough fern
white citrus
cloud dawn
unkempt canyonBOT
#
Nah.

No documentation found for the requested symbol.

cloud dawn
tough fern
cloud dawn
#

Pro not using the base API, Pro it's actually pretty gut

#

If you can find a con lmk

tough fern
slate swan
#

yes

cloud dawn
tough fern
cloud dawn
slate swan
#

i have a dashboard running with fastapi and hikari

slate swan
cloud dawn
cloud dawn
tough fern
slate swan
#

but fr just use fastapi, much better than flask

#

it's easy too

tough fern
slate swan
#

yes

#

it supports jinja templates as well

tough fern
#

send me a bit of its code

slate swan
#

you can find hikari related code in discord_rest.py and fastapi stuff in app.py

cloud dawn
#

If this had migrations it would be a true masterpiece.

slate swan
#

is it a bug in which bot react's twice?

cloud dawn
#

Sounds like a feature.

slate swan
#

i mean

cloud dawn
#

Fr tough; check task manager, your bot is likely running twice.

slate swan
#

oh yeah 💀

#

vsc is glitched

cloud dawn
#

Did you use any CTRL+ commands?

slate swan
#

yea

cloud dawn
#

Yeah most likely you used CTRL+Z what suspends a process not kills.

#

CTRL+C is kill

slate swan
#

ic

pliant gulch
#

That's like Pizza with no Cheese

slate swan
#

and inline css at some places

white citrus
slate swan
marble rampart
#

how can i fully close a bot and not get an error because when i do any of these:

        await client.loop.stop()
        await client.loop.close()
        await client.close()

its shows error:
Cannot close a running event loop
what do i do ?

obsidian kindle
#

hey yall

#

I ran my discord bot code but it returned with the error
AttributeError: module 'discord' has no attribute 'Intents'

lament mesa
#

maybe you've downloaded an older version

#
import discord

print(discord.__version__)``` run this to check the version
signal stone
static holly
#

what is it?
Import "discord_slash" could not be resolved

import discord
from discord_slash import SlashCommand
from discord.ext import commands

import os
from dotenv import load_dotenv
lament mesa
slate swan
slate swan
unkempt canyonBOT
#

class discord.app_commands.CommandTree(client, *, fallback_to_global=True)```
Represents a container that holds application command information.
obsidian kindle
#

I think I use the latest version

#

!pypi discord

unkempt canyonBOT
obsidian kindle
#

I use this one

slate swan
slate swan
static holly
naive briar
#

Why did they publish that package in the first place

slate swan
#

it's owned by danny as well, probably just to occupy the discord namespace on pypi

naive briar
#

Interesting

slate swan
static holly
# slate swan

i need to replace class xxx(commands.Cog) with this class ?

slate swan
#

...

#

it's not related to cogs

#

discord_slash is useless as for now

obsidian kindle
#

I tried reinstalling it @slate swan

#

Showed an error

naive briar
#

Send the error

unkempt canyonBOT
#

Hey @obsidian kindle!

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

slate swan
#

!pip idna

unkempt canyonBOT
#

Internationalized Domain Names in Applications (IDNA)

slate swan
#

install this, seems like your poetry is broken

obsidian kindle
#

Showed w similar error

naive briar
#

Then send the error

obsidian kindle
#

^ for idna

slate swan
#

your poetry is broken then

#

yet another reason to why not use replit

obsidian kindle
#

what do I do now

obsidian kindle
#

ill just copy the codes in them and use that instead

slate swan
#

just use a local ide for coding

#

vscode pycharm or something

obsidian kindle
#

what do you recommend

slate swan
#

i use vscode

obsidian kindle
#

it works fine in that?

slate swan
#

any editor will work just fine

obsidian kindle
#

except replit XD

slate swan
#

replit is bound to python 3.8 by default and bugs often

#

you can't do much about it if you don't know nix

obsidian kindle
#

just copying the code in vscode will work right

#

apart from installing the other packages

slate swan
#

yes

#

you'll have to install python on your device ofcourse.

obsidian kindle
slate swan
#

yeah that is needed as well

#

but you'll have to install the python interpreter too

obsidian kindle
#

what

slate swan
#

code doesnt run magically with a run button

#

there's resources required for that

#

you'll have to install a particular language's compiler for the language's file to run

obsidian kindle
#

I have python installed

#

how do I install the latest discord @slate swan

slate swan
obsidian kindle
# slate swan pip install discord.py

showed an error

pip : The term 'pip' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the
spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:1 char:1

shrewd fjord
#

not sure about the command

naive briar
#

No module named 'install'

obsidian kindle
#

um

#

what do I do now

naive briar
#
python -m pip install discord.py
#

Or run getpip

slate swan
#

any one of them should work

#

if they dont then you dont have pip

gusty flax
slate swan
#

i was talking about languages in general yeah

obsidian kindle
#

I have python

obsidian kindle
slate swan
#

replace ... with the package you want to install (discord.py) lol

obsidian kindle
#

oh forgot lol

#

should I update pip tho

slate swan
#

if you wish

obsidian kindle
#

it would work without updating?

#

bot = commands.Bot(command_prefix='!')
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: BotBase.init() missing 1 required keyword-only argument: 'intents'

#

this was the error it returned

#

am I missing something in the code?

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.

shrewd fjord
#

Intents are now required kwarg in new discord.py v2.0

obsidian kindle
#

its showing invalid sytax for import discord lol

gusty flax
shrewd fjord
obsidian kindle
#

SyntaxError: invalid syntax

pip install discord.py
File "<stdin>", line 1
pip install discord.py
^^^^^^^
SyntaxError: invalid syntax

#

I had just installed discord

gusty flax
obsidian kindle
gusty flax
#

did u try what @shrewd fjord said with just python -m pip install discord.py

obsidian kindle
#

python -m pip install discord.py
File "<stdin>", line 1
python -m pip install discord.py
^^^
SyntaxError: invalid syntax

gusty flax
#

are u running that in terminal, cmd, or in code

obsidian kindle
#

terminal

gusty flax
#

it looks like ur running code

#

press control + c

#

and do it again

vagrant raft
#

python print ("hello world!")

obsidian kindle
vagrant raft
obsidian kindle
#

I did ctrl +c

gusty flax
vagrant raft
obsidian kindle
#

like, just got to the window and press ctrl +c?

vagrant raft
obsidian kindle
#

done

gusty flax
#

did it work?

vagrant raft
#

python print ("hello world!")

hushed galleon
shrewd fjord
#

...

gusty flax
#

so pressing control + c leaves that

vagrant raft
#

python -m print ("hello world!")

shrewd fjord
#

Unless he changed keybinds 💀

hushed galleon
#

well keyboard interrupt doesnt get you out of an interactive interpreter, its usually ctrl+D or ctrl+Z

obsidian kindle
obsidian kindle
gusty flax
obsidian kindle
#

then why is it showing syntax error

#

I ran it again

gusty flax
#

can u send a screenshot

hushed galleon
#

syntax error means your python code has a syntax error, not that you have a missing library

tawdry swallow
obsidian kindle
shrewd fjord
gusty flax
tawdry swallow
#

Oh god

obsidian kindle
#

?

gusty flax
hushed galleon
#

that snippet is showing linter warnings, but not exactly a syntax error...

obsidian kindle
hushed galleon
#

do you have multiple versions of python installed?

shrewd fjord
#

It's vs code

obsidian kindle
#

yes

gusty flax
#

thank the lord

obsidian kindle
#

then why

tawdry swallow
#

I had the same problem

obsidian kindle
#

is it showing the syntax error

tawdry swallow
#

I couldnt fix it so I just moved to pycharm lol

gusty flax
#

@obsidian kindle use a venv

obsidian kindle
#

what?

gusty flax
shrewd fjord
#

Can u show ur file structure?

gusty flax
shrewd fjord
#

It's going to create virtual env for u

#

And on env folder u can install all following libraries

#

!venv

unkempt canyonBOT
#
Virtual Environments

Virtual environments are isolated Python environments, which make it easier to keep your system clean and manage dependencies. By default, when activated, only libraries and scripts installed in the virtual environment are accessible, preventing cross-project dependency conflicts, and allowing easy isolation of requirements.

To create a new virtual environment, you can use the standard library venv module: python3 -m venv .venv (replace python3 with python or py on Windows)

Then, to activate the new virtual environment:

Windows (PowerShell): .venv\Scripts\Activate.ps1
or (Command Prompt): .venv\Scripts\activate.bat
MacOS / Linux (Bash): source .venv/bin/activate

Packages can then be installed to the virtual environment using pip, as normal.

For more information, take a read of the documentation. If you run code through your editor, check its documentation on how to make it use your virtual environment. For example, see the VSCode or PyCharm docs.

Tools such as poetry and pipenv can manage the creation of virtual environments as well as project dependencies, making packaging and installing your project easier.

Note: When using PowerShell in Windows, you may need to change the execution policy first. This is only required once per user:

Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
hushed galleon
# obsidian kindle is it showing the syntax error

it is not a syntax error, its indicating that the python environment that vscode has selected doesnt have the modules installed - if you click the Python version on the bottom right of vscode you should see a list of python versions, have you made sure its selected the same python that you installed discord.py to?

gusty flax
# shrewd fjord python -m venv env

^ ur interpreter will be installed here, and all of ur libs. Everything is enclosed, so u wont get issues with it not being recognized.

obsidian kindle
hushed galleon
#

what is the actual error that shows up when you try to run your code?

shrewd fjord
#

Hm gud ques

obsidian kindle
#

bot = commands.Bot(command_prefix='!')
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: BotBase.init() missing 1 required keyword-only argument: 'intents'

hushed galleon
#

so the modules are correctly installed, you just need to fix the intents

obsidian kindle
#

intents are correct tho

gusty flax
hushed galleon
#

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

gusty flax
#

here