#discord-bots

1 messages · Page 113 of 1

silent ridge
#

and I did the command !cr

hushed galleon
#

does the bot have permission to read messages where you were sending the message?

silent ridge
#

yes admin perms

hushed galleon
#

code seems to be correct for 1.7.3

#

does the bot show up as online too?

silent ridge
hushed galleon
#

in the member list

silent ridge
#

oh yes, the bot goes online

#

but doesn't respond to my messages

slate swan
#

anyoen know how to fix this?

2022-10-23 20:22:34 WARNING discord.ext.commands.bot Privileged message content intent is missing, commands may not work as expected.

silent ridge
#

in the terminal, and can you screenshot that?

slate swan
#

Yeah

#

ignore the random stuff i accidently installed requirements from a different folder

silent ridge
#

okay do

hushed galleon
#

e.g. ```py
intents = discord.Intents.default()
intents.message_content = True

client = discord.Client(intents=intents)```

slate swan
#

did that already

silent ridge
#

maybe same problem like me

hushed galleon
#

nah the logger message would imply that it went online

slate swan
#

so why doesnt mine work?

hushed galleon
#

can you show the code for your intents and the bot constructor?

slate swan
#
from discord.ext import commands
import random
import os


intents = Intents.default()
intents.members = True

client = commands.Bot(command_prefix='.', intents=intents)
token = "my token is here usually"


@client.event
async def on_ready():
    print("online")

client.run(token)```
#

thats all i have

#

2022-10-23 20:28:12 WARNING discord.ext.commands.bot Privileged message content intent is missing, commands may not work as expected

#

and thats the error i get

hushed galleon
#

i tested your code with 1.7.3 and didnt have any problem with it

hushed galleon
slate swan
slate swan
#

ok

#

ill try right now

#

hi

silent ridge
#

let me install it again

slate swan
#

Is there anyone who can help him?

hushed galleon
# slate swan

the error says that the variable filename wasnt defined before it tried replying to the message

slate swan
#

@hushed galleonerror is gone but ima test if it works

silent ridge
hushed galleon
#

hm, does the message content intent in the dev portal apply retroactively for older gateway versions?

slate swan
#

@hushed galleonworks tysm

hushed galleon
hushed galleon
silent ridge
#

it worked, really appreciated. Thanks for the help buddy!

light night
#

Not yet i was thinking about it, but I was unsure if it was the best solution

and if it failed, I was unsure, how to replace message with interaction.followup and then doing it from there

slate swan
slate swan
slate swan
#

ahhh okay.

prisma prism
#

Hi Guys!
I'm having an issue with discord embeds and using pages
The issue i'm getting is, it just adds the info from the second page onto the first page, it doesn't clear the first page first

#
        pages = []
        n = 4
        new_main_Values_list = [temp_embed_values_list[i * n:(i + 1) * n] for i in range((len(temp_embed_values_list) + n - 1) // n)]
        for itemy in new_main_Values_list: #main list loop
            for item in itemy: #sub lists loop
                C +=item
            page = discord.Embed(title='Page 1/3', description='Description', colour=col)
            page.add_field(name=None, value=C)
            pages.append(page)
        print("4")
        message = await ctx.send(embed=pages[0])
        await message.add_reaction('⏮')
        await message.add_reaction('◀')
        await message.add_reaction('▶')
        await message.add_reaction('⏭')

        def check1(reaction, user):
            return user == ctx.author
        i = 0
        reaction = None
        print("5")
        while True:
            if str(reaction) == '⏮':
                i = 0
                await message.edit(embed=pages[i])
            elif str(reaction) == '◀':
                if i > 0:
                    i -= 1
                    await message.edit(embed=pages[i])
            elif str(reaction) == '▶':
                if i < 2:
                    i += 1
                    await message.edit(embed=pages[i])
            elif str(reaction) == '⏭':
                i = len(itemy)
                await message.edit(embed=pages[i])

            print("6")
            try:
                reaction, user = await bot.wait_for('reaction_add', timeout=100.0, check=check1)
                await message.remove_reaction(reaction, user)
                print("7")
            except:
                print("Breaking 1234")
                break
        await message.clear_reactions()
#

this is the bit of code that's giving the issue

slate swan
#

Can anyone explain why my custom .help command isnt working this is the code.

@client.command(pass_context=True)
async def help(ctx):
    author = ctx.message.author

    embed = discord.Embed(
        colour = discord.Colour.orange()
    )

    embed.set_author(name='Help')
    embed.add_field(name='.ping', value='Shows Bot Delay', inline=False)

    await client.send_message(author, embed=embed)```
prisma prism
#

what's the error you get

slate swan
#

discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Bot' object has no attribute 'send_message'

hushed galleon
#

send_message doesnt exist in the recent versions of dpy

slate swan
#

so what is the new way?

prisma prism
#

await ctx.send(embed = embed)

hushed galleon
#

for DMing, you'd use .send() on the author object directly

slate swan
#

so its like .help and it shows the commands

hushed galleon
#

oh, i thought you actually wanted to send to the author given your usage of it

#

ctx.send() sends to the channel the command was invoked from like blue's example

#

er, no

slate swan
#

await ctx.send(author, embed=embed)

hushed galleon
#

author shouldnt be provided in this case

slate swan
#

oH

hushed galleon
#

otherwise it would become the content of the message

slate swan
#

It works though?

#

I just tested it like that and it worked

prisma prism
slate swan
#

Oh yes its better now

#

ty

hushed galleon
prisma prism
#

sure

#

So this is the command displaying, and it looks fine

#

then when I press to go to the next page

#

I get this

#

and then if I press a third time, it gives embed size error, because they are limited to 1024 iirc

#

I think somethings wrong with the embed, like it's not giving separate ones for different pages

hushed galleon
#

hm, assuming C is a string, it doesnt seem you're resetting it across each page, meaning it accumulates across each page

#

also the title is statically set to 'Page 1/3', so you wont see that updating

prisma prism
#

oh yeah, I was gonna fix that later

#

ty though

hushed galleon
#

ah ok

prisma prism
#

can I make C global and then reset it before I print("4") ?

hushed galleon
#

why would you need C to be global?

#

if its only used in the page embed you can simply redefine it after each iteration of your main list

slate swan
prisma prism
#

ahh thank you

slate swan
prisma prism
#

That worked perfectly! Thank you so much!

slate swan
#

does dpy gh not have examples for cogs?

hushed galleon
#

the documentation does but not the github

slate swan
#

ahhhh

hushed galleon
#

same for extensions, but unfortunately doesnt show extensions combined with cogs despite its frequent use case

slate swan
#

yeeee thats what i was looking for for this guy

torpid hare
#

is there any specific reason that my bots status works perfectly on windows but when i transfer it to my pi it just doesnt work my windows python version is 3.10.5 and my raspberry pis python version is 3.9.2

slate swan
#

wdym by "status"

stuck rivet
#

so discord changed how do you add a bot to server now

hushed galleon
#

you generate an invite link for the bot and have people click it

#

afaik nothing's changed

#

there's only the new Add to Server button on the bot's profile

#

if you want to include that feature you can enable it in the OAuth2 page on the dev portal

stuck rivet
#

yeah i enabled requires oauth2 grant by mistake that was my issue

hushed galleon
#

ah you meant your invite wasnt working

stuck rivet
#

yeah

#

why cant discord bots share screens?

sick birch
stuck rivet
#

are self bots that can do it legal?

hushed galleon
#

self bots are against discord's guidelines, so you're out of luck

#

unless you're able to use another streaming service or make your own

pulsar bridge
#

How would I add cool-downs, timers and delays to commands?

  • Cool-downs as in: You can’t use this command again for another 10 minutes

  • Timers as in: This command will execute every time “Python” is mentioned for the next 30 seconds

  • Delays as in: After 40 seconds, this part of the command will run. But without using time.sleep cause I don’t want to pause the entire program

hushed galleon
#

cooldowns are included with the commands extension, and delays are built into asyncio with asyncio.sleep(), but your timers idea would need to be done manually with a listener

sick birch
#

Timers might be a little bit more effort, because you'll need to store some sort of state on what time the timer was started, and check if the current time is less than start time + the timer length

pulsar bridge
#

Gotcha, I remember someone telling me about that a while back… Hmmmm

Commands Extension, I’ll have to read on

And Listeners? Am unfamiliar with the term

hushed galleon
#

oh, you havent used the commands extension before?

pulsar bridge
#

Got a db set up for it though

sick birch
#

And use something like a global check or just a plain old if statement

pulsar bridge
hushed galleon
slate swan
pulsar bridge
#

Ooh, yea I know them, didn’t know the term was listeners derp My bad

hushed galleon
#

listeners are distinct from basic event handlers

pulsar bridge
hushed galleon
#

discord.Client supports event handlers with the @event decorator while commands.Bot adds a listen() decorator which you can have multiple of for the same event, unlike the event handler

sick birch
#

I'm not aware of that library but I don't think there's a need to

#

It should be relatively simple logic if you handle it yourself

pliant gulch
sick birch
#

Store start_time = datetime.datetime.now() when something happens, then later check (datetime.datetime.now() - start_time).seconds > 1800, and start the next timer only if so

#

(1800 seconds is 30 minutes btw)

pulsar bridge
#

Looks like Extra homework tonight Kek

hushed galleon
#

if the timer only lasts 30 seconds as originally asked, i would simplify it to a dictionary

#

or perhaps a set

#

then have the command add the channel ID to the set, sleep 30s, and remove the channel ID, that way your listener simply has to check if the channel ID is there to know that the command is active

pulsar bridge
#

Why not try all the solutions out?
Let’s see which one works best MiyanoHey

torpid hare
upbeat gust
#

and where are you setting this

torpid hare
#

oops

slate swan
#

are the paths different?

torpid hare
#

i didnt change anything

slate swan
#

are u storing the game locally?

torpid hare
#

yea

slate swan
#

can u show code how ur setting

torpid hare
#

yea

#

im not the best programmer so dont mind if the code is messy

unkempt canyonBOT
#

Hey @torpid hare!

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

torpid hare
#

ok

#

i thought it couldve been the version of python i have installed on my raspberrypi 3.9.2 i tried upgrading it but it broke everything and i had to reinstall the os

upbeat gust
torpid hare
#

yes

#

it chooses a random game every minute from the files

upbeat gust
slate swan
#

idk much ab raspberrypi but is the OS not different?

chilly dove
#

@torpid hare if the name parameter in discord.Streaming is empty the bot will appear to do nothing without an error double check that its getting more then nothing

torpid hare
torpid hare
torpid hare
#

if it was empty it isnt a game

upbeat gust
slate swan
torpid hare
#

it works on windows

#

yea

upbeat gust
chilly dove
#

well if its exactly the same code running on both windows and the pi and one works but the other doesnt thats the only difference is the data that you are importing

#

all i got

torpid hare
#

i tried it with different data aswell

#

didnt work then either

slate swan
#

u tried pointing directly to the path?

torpid hare
#

the only time it did work was when i put in a a string like so await bot.change_presence(activity=discord.Streaming(name="Hello", url=my_twitch_url))

chilly dove
#

i would put print statements to see what the data variable is before setting the presence

torpid hare
slate swan
#

mhm

torpid hare
#

yes it is

chilly dove
#

is it works with the hello then its 100% where you are pulling that data var from

torpid hare
#

then why is it consistently working on windows?

slate swan
#

try to use the FULL path on ur rpi

torpid hare
#

alright

chilly dove
#

on windows its properly pulling the data on the pi its not

upbeat gust
#

and also, do you have logging setup?

torpid hare
#

i do not

#

oml

torpid hare
slate swan
#

yup figured

torpid hare
#

thank you so much

#

i owe you one

upbeat gust
# torpid hare i do not

Using dpy 2.0 and not getting any errors? This is on purpose, the library now uses logging to send errors but only if you're using Client/Bot.run. More about that in ?tag defaultlogging.

It's recommended to setup logging yourself if you aren't using .run or use the utils.setup_logging helper function: just put discord.utils.setup_logging() anywhere in your running file. Docs: https://discordpy.readthedocs.io/en/stable/api.html#discord.utils.setup_logging

but I can't use Client/Bot.run!
You can! You can load cogs and do other stuff in the newly added setup_hook method that is called once after the bot logs in, more about that and how to implement it in ?tag setuphook.

#

please get the setup so you see your errora

torpid hare
#

i will do that, thanks

upbeat gust
# torpid hare cause i couldnt think of a better way of doing it sorry

have the names in a dict like

games = {
  1: "foo",
  2: "bar"
  ...
}```
And get from the key
Or even just use a list and the index

All of the duplicate lines can all just be used once
There's no reason they need to be in the if (or for you to have ifs at all)

Your 400 lines could be like 10
inland gulch
#

hi

torpid hare
#

that does make more sense

swift trench
#
@client.command()
async def geninv(ctx, channel: discord.TextChannel = None):
    user = ctx.author
    await ctx.message.delete()
    if channel is None:
        invitelink = await ctx.channel.create_invite(max_uses=300,unique=True)
        await user.send(f"invite in {ctx.channel.guild}!\n{invitelink}")
    else:
        invitelink = await channel.create_invite(max_uses=300,unique=True)
        await user.send(f"invite in {ctx.channel.guild} invite goes to {channel}!\n{invitelink}")
#

I have this and it works fine but how can I make it so I can do $geninv id

#

instead of $geninv #channel

#

ive already tried but i get multiple errors

chilly dove
#

@swift trenchassuming you are using bot instead of client that should convert a id to a text channel whats the error?

topaz helm
#

Do you have the kick/ban order to give me, please, but let it go smoothly???

swift trench
#

@chilly dove im not changing that anymore but can you help me with

@client.command()
async def channels(ctx):
  channel = list(ctx.guild.channels)
  c = str(channel)
  em = discord.Embed(title='ALL CHANNELS/CATEGORYS', description=f"channels\n{c}")
  await ctx.send(embed=em)
#

and make it return a list

topaz helm
#

@swift trench
Do you have the kick/ban order to give me, please, but let it go smoothly???

swift trench
#

shut

#

and look it up

chilly dove
glad cradle
glad cradle
swift trench
#
@client.command()
async def channels(ctx):
  channel = ctx.guild.channels
  for c in channel:
    c.append(channel)
  em = discord.Embed(title='ALL CHANNELS/CATEGORYS', description=f"channels\n{channel}")
  await ctx.send(embed=em)
#

@chilly dove

#

i tried this

glad cradle
#

c is not defined, or rather you are trying to use append on something that is not a list

chilly dove
#

try this py channel_names = [channel.name for channel in ctx.guild.channels]

swift trench
#

ok

#

works 👍

#

any way to space out categorys from text channels?

chilly dove
#

the guild instance has .text_channels which will only return text channels and not all channels

swift trench
#

@chilly dove

#

what if I wanted it to return like

#

1
2
3
4

#

or maybe
1 text
2 category
3 voice
4 category

chilly dove
#

well you can check if something is one of those by using something like py isinstance(channel, discord.TextChannel) and substitute any of these:
TextChannel
VoiceChannel
CategoryChannel
StageChannel
ForumChannel
for text channel

swift trench
#

could you help @chilly dove

#

just making it
like
this

jagged widget
#

i wanna ask something that on message event and client .command are not responding together

swift trench
#

huh

chilly dove
paper sluice
#

or just change@bot.event to @bot.listen()

topaz helm
#

I also have a question where do I put the commands in main.py?

#

I'm new to bots

#

I also have a question where do I put the commands in main.py?

slate swan
glad cradle
jagged widget
topaz helm
#

do you have an order to say? so that I write, I say and the bot says

vale wing
#

"Order to say" what

limber pagoda
vale wing
#

🫦🦶

limber pagoda
#

Bot replies heeeh GA we

vale wing
#

Make an arg and send the arg

#
async def say(ctx, *, stuff):
    await ctx.send(stuff)```
cloud dawn
loud junco
#

erm is this even a thing 💀

hot cobalt
#

oh dear

#

I'd like to know who on earth is asking that

lament mesa
#

good luck querying it

tough lance
#

How to use slash subcommands in cogs? (disnake)

loud junco
maiden fable
hot cobalt
vocal aspen
#

Couple months ago I helped develop an AI chat bot that utilized OpenAI's GPT-3 and implemented it into discord. So far it's doing pretty well

maiden fable
#

Nice
But the credits offered are hella limited, I also tried

vocal aspen
#

Credits?

maiden fable
#

Yea, when I tried it, it was still in Closed Beta and u were offered a limited amount of credits, which are used to generate responses. Once those are finished, u gotta buy them to keep using the AI

vocal aspen
#

I think I know what you're talking about. The only thing I regularly pay for are the servers to upkeep the bot so I'm not sure if that's still a thing

#

Would you be interested in trying out the bot though?

slate swan
#

is it on_guild_channel_add or on_guild_channel_create ?

silent ridge
#

does anyone know why after 3/4 minutes my bot doesn’t verify anymore?

#

my bot is still running (online status) so I don’t understand it

brazen raft
ripe blaze
#

Is there a way to get invited users through an invite link?

zealous jay
#

Who joined using that url?

ripe blaze
#

is that possible?

zealous jay
#

maybe you can get the invite url that was used when a new user joins your server

#

if not you could save invites and how many times they were used and when a user joins check which invite has been updated

scarlet linden
#
  File "main.py", line 2, in <module>
    from discord import app_commands
  File "/home/runner/pythondisc/venv/lib/python3.8/site-packages/discord/app_commands/__init__.py", line 12, in <module>
    from .commands import *
  File "/home/runner/pythondisc/venv/lib/python3.8/site-packages/discord/app_commands/commands.py", line 51, in <module>
    from ..enums import AppCommandOptionType, AppCommandType, ChannelType, Locale
ImportError: cannot import name 'AppCommandOptionType' from 'discord.enums' (/home/runner/pythondisc/venv/lib/python3.8/site-packages/discord/enums.py)
 

why does this happen when i import app_commands from discord

zealous jay
slate swan
scarlet linden
#

ill try it

zealous jay
#

i think app_commands is for slash commands

scarlet linden
zealous jay
#

idk if its the same thing

scarlet linden
zealous jay
#

yeah its probably app_commands

gloomy meadow
#

@sick birch I just thought about it. Could I maybe access the buffer where all the bot's execution orders are stored and remove certain ones?

wispy trail
#

how i manage cooldowns replies for individual commands in cogs?

cloud dawn
small sentinel
#

can anyone rate my code's optimization ? I'm a noob and am looking towards writing nice code because I'm working on a very big project

#

variable names are in french so a french developer would understand way better

cloud dawn
#

I recommend coding in English.

small sentinel
#

that's a totally valid recommendation but since I started in french I'm a bit lazy to change everything to english

#

but you're right it's helpful in these kind of situations where I'm sharing code with foreigners

cloud dawn
#

When asking for help it's easier, the library is already English so now it's a mix of. Other than that I recommend typehinting.

paper sluice
unkempt canyonBOT
#

When checking if something is equal to one thing or another, you might think that this is possible:

# Incorrect...
if favorite_fruit == 'grapefruit' or 'lemon':
    print("That's a weird favorite fruit to have.")

While this makes sense in English, it may not behave the way you would expect. In Python, you should have complete instructions on both sides of the logical operator.

So, if you want to check if something is equal to one thing or another, there are two common ways:

# Like this...
if favorite_fruit == 'grapefruit' or favorite_fruit == 'lemon':
    print("That's a weird favorite fruit to have.")

# ...or like this.
if favorite_fruit in ('grapefruit', 'lemon'):
    print("That's a weird favorite fruit to have.")
cloud dawn
#

Other than that I can't really recommend anything else since I have no clue what this does.

small sentinel
#

changed to

elif destination in ['chemin','route']:
paper sluice
#

Maybe space your code a little bit, leave like a line after a block of code

if ...:
  # ...
else:
  # ...

# rest of the code ...
small sentinel
#

okay will do

small sentinel
white citrus
#

Can someone help?

silent portal
#

Is there a on_channel_delete event or something like that?

fallow mauve
#

is there a way to make a discord bot start my aternos minecraft server by use of a command?

glad cradle
unkempt canyonBOT
#

discord.on_guild_channel_delete(channel)``````py

discord.on_guild_channel_create(channel)```
Called whenever a guild channel is deleted or created.

Note that you can get the guild from [`guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.GuildChannel.guild "discord.abc.GuildChannel.guild").

This requires [`Intents.guilds`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.guilds "discord.Intents.guilds") to be enabled.
silent portal
#

ty

vocal snow
maiden fable
#

!pypi python-aternos

unkempt canyonBOT
maiden fable
#

@fallow mauve

vocal snow
#

That definitely violates aternos tos

maiden fable
#

But then, its prolly against ToS

#

Idk I just saw someone using it

fallow mauve
#

bcs i just need a way for my members to run my server when they wanna get on

#

i wouldnt be abusing it or anything

#

but idk if that would matter

robust rune
#

@fallow mauve Help

#

@full rampart Help please

sick birch
#

Please stop pinging random people

warped mirage
#
in on_member_join
    embed = discord.Embed(colour=0xFF00FF, description=f"Welcome to sever {member.name}. The current member count is {len(list(member.guild.members))}", timestamp=datetime.datetime.utcfromtimestamp(1553629094))
AttributeError: type object 'datetime.datetime' has no attribute 'datetime'``` how can I fix?
sick birch
#

I think it's just datetime.utcfromtimestamp

#

You already have from datetime import datetime

sick birch
#

Plus your bot is going to need a VPS anyway so just run your Minecraft server on it

#

2 in 1

warped mirage
keen dust
#
timestamp = datetime.utcfromtimestamp()
warped mirage
#

Btw

#
embed.set_thumbnail(url=f"{member.avatar.url}")``` it says object has no url
vocal snow
#

then maybe member.avatar is None

#

use display_avatar

warped mirage
#

wouldn't member.avatar.icon.url work?

#

or should i do display_avatar

#

Oh yea it works its cuz a user didn't have a avatar, is it possible to make it ignore that error and just show no avatar or smth?

silent portal
#

it should display the default avatar aswell

warped mirage
#

ah ok

fallow mauve
slate swan
bright wedge
slate swan
ripe blaze
#

Where can I host my discord bot?

sick birch
ripe blaze
#

thanks!

bitter jewel
#
@bot.listen()
async def on_message(ctx):
    if any(x in ctx.content.lower() for x in [".cumpara"]):
        log_data = load_stats()
        authorid = str(ctx.author.id)
        author = str(ctx.author)
        if authorid {'cumpara'} in log_data:
            log_data[str(ctx.author.id)]['cumpara'] += 1
            save_stats(log_data)
        else:
            log_data[str(ctx.author.id)] = {}
            log_data[str(ctx.author.id)]['cumpara'] = 1
            save_stats(log_data)
    
    if any(x in ctx.content.lower() for x in [".anuleaza"]):
        log_data = load_stats()
        authorid = str(ctx.author.id)
        author = str(ctx.author)
        if authorid {'anuleaza'} in log_data:
            log_data[str(ctx.author.id)]['anuleaza'] += 1
            save_stats(log_data)
        else:
            log_data[str(ctx.author.id)] = {}
            log_data[str(ctx.author.id)]['anuleaza'] = 1
            save_stats(log_data)
#

if authorid {'anuleaza'} in log_data:
code isnt working bcs this line

#

any idea whats wrong with it?

slate swan
#

Idk what your trying to achieve

bitter jewel
#

it has to log something like
{
id: "userid",
anulat/cumparat: how much times
}

wintry shoal
#

hey

#

why does it say "undefined name "commands""

#

when i put @lavish micamands.has_permissions(kick_members=True)

slate swan
#

Idk not sure

wintry shoal
slate swan
#

from discord.ext.commands import *

wintry shoal
#

i'll send my code

wintry shoal
# slate swan from discord.ext.commands import *
from discord import app_commands
from discord.ext import commands
from discord.ext.commands import *

class aclient(discord.Client):
    def init(self):
        super().init(intents=discord.Intents.default())
        self.synced = False

    async def on_ready(self):
        await self.wait_until_ready()
        if not self.synced:
            await tree.sync(guild = discord.Object(id = 1020363390272671805))
            self.synced = True
        print("We have logged in as {self.user}.")

client = aclient(intents=discord.Intents.default())
tree = app_commands.CommandTree(client)

@client.command()
@commands.has_permissions(kick_members=True)
async def kick(ctx, member: discord.Member, *, reason=None):
    if reason==None:
      reason=" no reason provided"
    await ctx.guild.kick(member)
    await ctx.send(f'User {member.mention} has been kicked for {reason}')```
slate swan
wintry shoal
#

says no attribute called command

slate swan
#

Remove commands.

#

How to host bot 24*7 free pls helppoo

#

Also ping if reply plis :)

wintry shoal
slate swan
#

🗿

wintry shoal
#

u can't host reliably for free prob

slate swan
#

Wdym by unreliable

#

😔

bright wedge
slate swan
#

Like they gonna take over my bot and destroy servers or smthn?

bright wedge
#

its not trusted

slate swan
#

I mean it's only me who uses the bot...👀

#

To like remind me to do stuff bcz im one forgetful little bitch

#

So i dont really need anything fancy unless the bot like goes offline every other day

#

Its not even in any server so atmost it'll just sabotage my dms or that one server we all have where we write random stuff like grocery lists and all

#

So i dont wanna spend moneh u feel me ¯_(ツ)_/¯

bright wedge
sick birch
#

Does it need to be online all the time?

slate swan
#

I mean like how else is it supposed to remind me to do stuff if i need to remember to turn it on to remind me ||duh🗿||

slate swan
faint mural
#

Just get a raspberry as an one time investment KogasaWink

slate swan
#

I don't earn atm legit living off my father's money so i cant spend on, well, anything at all tbh...🗿

zealous jay
#

How can I handle errors with d.py 2.0?

sick birch
zealous jay
#

If i remember correctly it wasn't implemented before

#

I mean in the version that supports slash commands

sick birch
#

Ohhh

#

Thought you meant prefix commands error handling

#

I think for the majority of the part it's the same

zealous jay
#

Is there any example?

shrewd apex
slate swan
#

Sorry, I have no plans on helping here as people have personal problems for unknown reasons and do not believe I help anyone or contribute to anything. They also go on and insult you in your back for no reasons, and I'd rather not have to interact with such type of people or see them while "helping" (apparently I don't) others.

Hence I won't help anymore, so that these people are happy.

south coyote
#

how do i make this so it uses the AI framework?

import discord


intents = discord.Intents.default()
intents.message_content = True
intents.members = True

client = discord.Client(intents=intents)


conversation = {
    "what is": "I don't know, I'm just a bot!",
    "think": "I don't think, I just do",
    "wtf": "Good question",
    "you had it": "Somebody must have swiped it! Is there another one?",
    "like": "I love lamp",
    "crickets": "It's pretty quiet in here",
    "yes": "That's amazing",
    "ping": "PONG!",
    "when": "Maybe a little later. I don't know yet. I'm kinda busy here",
    "who are you": "I'm a bot!",
    "load a bowl": "I'm down! Where's the lighter?",
    "you got some bud": "I thought you did!",
    "is it 4:20": "It's always 4:20 somewhere!",
    "how can we": "If I knew that we wouldn't be asking",
    "sup": "Chillin'",
    "what's up": "What is?",
    "that's smart": "I try my best",
    "sus": "I didn't do it. Nobody saw me do it. You can't prove anything!",
    "where": "Somewhere",
    "morning": "Good Morning!",
    "gm": "gm",
    "no way" : "I doubt it",
    "yes" : "I believe so",
    "wake and bake": "I'm down. load it up!",
    "smoke": "I got five on it!",
    "kind of bud": "the sticky icky son!",
    "how are you": "excellent, how are you?"
}


@client.event
async def on_ready():
    print(f'We have logged in as {client.user}')

@client.event
async def on_message(message):
    if message.author == client.user:
        return
    if message.channel.id != 1018756543816155187:
        return
#loops through the "conversation" dictionary to check if the keywords are used and if so responds accordingly
    for word, answer in conversation.items():
        if word in message.content.lower():
            await message.channel.send(answer.lower())
#offers help when the word "help" is entered
    if 'help' in message.content.lower():
        await message.channel.send("Try saying 'hello'")
#

i want to use the neuralintents module

slate swan
#

It's fine, hopefully you'll get the help needed from others. If you don't I'll eventually help again though I doubt for the reasons above

south coyote
#

i guess i just use this template huh?

shrewd apex
jaunty musk
#

how can I turn this ![gimmetail](https://cdn.discordapp.com/emojis/872298447393419294.webp?size=128 "gimmetail") into :gimmetail: ? I'm trying to set a variable of it.

#

i tried emoji.demojize(variable) and emoji.emojize(variable, language='alias') and niether seem to work :/

#

nvm, I just ended up using regular expression to filter it out lol

wintry shoal
#

anyone know why it won't mention the user and why it displays that at the start?

fading marlin
#

for the first one, you're probably not using the mention property. For the second one, you're passing an interaction object for whatever reason

#

result[0] apparently is a tuple

#

read the error :)

wintry shoal
fading marlin
#

no? that's the exact same thing as int(result[0]) and will throw the same exception. int returns an integer, as in a number, not a string. You should check why result[0] is a tuple instead of whatever you want it to be, or maybe you forgot that result is a nested tuple

wintry shoal
#

i may be wrong, but i think where you have
if result is None
maybe do
if result = None
cause that's what i use

fading marlin
wintry shoal
#
import discord
from discord import app_commands
from discord.ext import commands
from discord.ext.commands import has_permissions, MissingPermissions

class aclient(discord.Client):
    def init(self):
        super().init(intents=discord.Intents.default())
        self.synced = False

    async def on_ready():
        print("We have logged in as {self.user}.")
Intents = discord.Intents(messages=True, guilds=True)

client = discord.Client(intents=Intents)
tree = app_commands.CommandTree(client)

@tree.command(name="ban")
@commands.has_permissions(ban_members=True)
async def ban(ctx, member: discord.Member, *, reason: str):
    if reason==None:
      reason=" no reason provided"
    await ctx.channel.send(f"{ctx} <@!{member.id}> got banned for {reason}")
    await ctx.guild.ban(member)


client.run("token")```
fading marlin
#
await ctx.channel.send(f"{ctx} <@!{member.id}> got banned for {reason}")
wintry shoal
bitter jewel
#

What I wanted to make: When someone type those things on chat or dm he has to add +1 to 2 diff categories (if .cumpara has to add +1 to cumpara and the same thing for .anuleaza) but I'm getting errors trying to store info (also it has to autogenerate if theres nothing)

Code

@bot.listen()
async def on_message(ctx):
    if any(x in ctx.content.lower() for x in [".cumpara"]):
        log_data = load_stats()
        authorid = str(ctx.author.id)
        author = str(ctx.author)
        if authorid in log_data["cumpara"]:
            log_data[str(ctx.author.id)]['cumpara'] += 1
            save_stats(log_data)
        else:
            log_data[str(ctx.author.id)] = {}
            log_data[str(ctx.author.id)]['cumpara'] = 1
            save_stats(log_data)
    
    if any(x in ctx.content.lower() for x in [".anuleaza"]):
        log_data = load_stats()
        authorid = str(ctx.author.id)
        author = str(ctx.author)
        if authorid in log_data["anuleaza"]:
            log_data[str(ctx.author.id)]['anuleaza'] += 1
            save_stats(log_data)
        else:
            log_data[str(ctx.author.id)] = {}
            log_data[str(ctx.author.id)]['anuleaza'] = 1
            save_stats(log_data)

Error

raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
fading marlin
fading marlin
wintry shoal
#

i literally began discord bots today sry

fading marlin
bitter jewel
#

context ig

bitter jewel
wintry shoal
#

oh okay ty

bitter jewel
#

a database will just make it more complicated at that point fr

fading marlin
#

you sure it printed absolutely nothing? did it print some empty parenthesis ()?

fading marlin
bitter jewel
#

i dont even have my json file formatted

#

isnt that supposed to auto generate?

fading marlin
wintry shoal
#

ohh i see my mistake
it's the {ctx} in the formatted string causing the weird message

fading marlin
#

you should print it before trying to get the role, not after, otherwise you're gonna get an error and the print statement won't get executed

wintry shoal
#

thanks guys :)

bitter jewel
#

what lib i should use for mongo database

#

pymongo?

white citrus
#
Traceback (most recent call last):
  File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\client.py", line 502, in _run_event
    await coro(*args, **kwargs)
  File "c:\Discord\Maja Projekt\MajaSystem_Test\bot.py", line 209, in on_application_command_error
    raise error
  File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\application_command.py", line 863, in invoke_callback_with_hooks
    await self(interaction, *args, **kwargs)
  File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\cooldowns\cooldown.py", line 93, in inner
    result = await func(*args, **kwargs)
  File "c:\Discord\Maja Projekt\MajaSystem_Test\modules\information\cog.py", line 192, in userinfo
    e_view.from_message(interaction.message, timeout=None)
  File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\ui\view.py", line 260, in from_message
    for component in _walk_all_components(message.components):
AttributeError: 'NoneType' object has no attribute 'components'```
#
            button = nextcord.ui.Button(label="Show all Roles", style=nextcord.ButtonStyle.blurple)

            e_view = nextcord.ui.View(timeout=None)
            e_view.from_message(interaction.message, timeout=None)
            
            async def button_callback(interaction):
                embed_roles = nextcord.Embed(title="Roles", description="\n".join(reversed([f'> {r.mention}' for r in filter(lambda role: not role.is_default(), member.roles)])))

                button.disabled = True
                button.style = nextcord.ButtonStyle.grey
                await interaction.edit_original_message(embeds=[userinfo, embed_roles], view=e_view(interaction.message, timeout=None))
            
            async def button_timeout(interaction):
                button.disabled = True
                button.style = nextcord.ButtonStyle.grey
                await interaction.edit_original_message(view=e_view)  
            
            button.callback = button_callback
            button.timeout = button_timeout
            
            view = nextcord.ui.View()
            view.add_item(button)
fading marlin
bitter jewel
#

at that point ill just giveup with that ig

fading marlin
#

that's a tuple with an integer inside of it

bitter jewel
#

thru api

fading marlin
#

well, I'm assuming you know what a tuple is, so I don't think you really need my help

fading marlin
bitter jewel
white citrus
wintry shoal
#

how do i turn my ban message into an embed then?

bitter jewel
#

i mean i can manually but im losing time at that point fr

fading marlin
#

correct, and you can access the contents inside the tuple how?

#

you probably want an integer instead of a string

fading marlin
fading marlin
# wintry shoal how do i turn my ban message into an embed then?

!d discord.abc.Messageable.send (checkout the embed kwarg). Fwiw you should try not making ban commands, Discord already does this, so there's really no point. Anywho, if you want your message to be an embed, you need to pass an Embed object to the embed kwarg in whatever method you're using the reply

unkempt canyonBOT
#
await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Sends a message to the destination with the content given.

The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` parameter must be provided.

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. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.10)") of [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File "discord.File") objects. **Specifying both parameters will lead to an exception**.

To upload a single embed, the `embed` parameter should be used with a single [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") object. To upload multiple embeds, the `embeds` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.10)") of [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") objects. **Specifying both parameters will lead to an exception**.
fading marlin
#

no, result[0] returns a tuple, you gotta index the tuple returned by result[0]

wintry shoal
fading marlin
white citrus
bitter jewel
#

how can i send message to a specified user?

white citrus
wintry shoal
#

hmm
where's the syntax error
embed = discord.Embed(title="Banned Successfully.", description="<@!{member.id}> got banned for {reason}", color=discord.Color.random())

bitter jewel
white citrus
fading marlin
fading marlin
white citrus
fading marlin
#

wdym?

wintry shoal
white citrus
#

If not do you have the paste command? @fading marlin

fading marlin
fading marlin
bitter jewel
#
@bot.listen()
async def on_message(ctx):
    user = await ctx.get_user('852673731900735508')
    if any(x in ctx.content.lower() for x in [".cumpara"]):
        await user.send(ctx.author.id+" a cumparat un numar.")
    
    if any(x in ctx.content.lower() for x in [".anuleaza"]):
        await user.send(ctx.author.id+" a anulat un numar de telefon.")
  File "D:\etc\devv\bilenatorul\main.py", line 258, in on_message
    user = await ctx.get_user('852673731900735508')
AttributeError: 'Message' object has no attribute 'get_user
#

hell nah

fading marlin
#

also, get isn't a coroutine

white citrus
wintry shoal
fading marlin
#

I am telling you how. Index the first item

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.

fading marlin
white citrus
fading marlin
#

the command should be just fine I guess

wintry shoal
#
    embed = discord.Embed(title="Banned Successfully.", description=f"<@!{member.id}> got banned for {reason}", color=discord.Color.random())
    ^
SyntaxError: invalid syntax
fading marlin
#

line above might be causing some issues?

bitter jewel
#
@bot.listen()
async def on_message(ctx):
    user = bot.get_user('852673731900735508')
    if any(x in ctx.content.lower() for x in [".cumpara"]):
        await user.send(ctx.author.id+" a cumparat un numar.")
    
    if any(x in ctx.content.lower() for x in [".anuleaza"]):
        await user.send(ctx.author.id+" a anulat un numar de telefon.")

tried adding/removing awaits still getting errors

#
TypeError: object NoneType can't be used in 'await' expression```
such as this one
fading marlin
unkempt canyonBOT
wintry shoal
fading marlin
wintry shoal
#

i just put it anywhere i didn't know

#

it's in the middle of my ban member command 💀

fading marlin
bitter jewel
#
@bot.listen()
async def on_message(ctx):
    user = await bot.get_user(852673731900735508)
    if any(x in ctx.content.lower() for x in [".cumpara"]):
        await user.send(ctx.author.id+" a cumparat un numar.")
    
    if any(x in ctx.content.lower() for x in [".anuleaza"]):
        await user.send(ctx.author.id+" a anulat un numar de telefon.")```

user = await bot.get_user(852673731900735508)
TypeError: object User can't be used in 'await' expression

fading marlin
#

get_user isn't a coroutine

bitter jewel
#

what do u mean

fading marlin
#

you can only await coroutines, get_user isn't one

#

the law requires me to say that you should report to Discord I guess

bitter jewel
#
await user.send(ctx.author.id+" a anulat un numar de telefon.")
TypeError: unsupported operand type(s) for +: 'int' and 'str'

code is upper..

fading marlin
bitter jewel
#

javascript can do that..

fading marlin
#

this isn't javascript lmao

bitter jewel
#

thanks

fading marlin
white citrus
fading marlin
white citrus
#

So you cant help me in this case

fading marlin
#

this just isn't a good implementation, that's all.
You're trying to call a class instance for some reason? (line 62). You should pass just e_view to your new view like you do in line 67. Also, you have to respond to interactions, so use interaction.response.edit_message instead of what you currently have

violet kraken
#

is there a way to make custom emojis bigger in embeds?

fading marlin
#

text-wise? no

violet kraken
#

what is that

fading marlin
#

description, field values (you can't have mentions/emojis anywhere else)

violet kraken
#

oh yea

#

so no way to makeit bigger

fading marlin
#

unless you use an image, no

violet kraken
#

hmm image, i don't know how it would work since i need to use multiple of them mixed with text

fading marlin
#

generate the text on top of an image and edit emoji sizes yeah, you'll have to stick with the size

violet kraken
#

damn

#

this is literally supposed to be x128 high but looks like 50

fading marlin
#

that looks really neat

faint mural
#

class Something(discord.ui.View):

quiet bronze
#

Is it possible to make python send messages with your own account?

#

so no bot that does it with an command. But if you run your code it sends "hello" from your account for example

sick birch
quiet bronze
#

ah okay, was trying to make an AI respont for you on discord, whatsapp etc but didnt know it was against their terms of service

slate swan
quiet bronze
#

is it also against the terms to check the message you received in python?

slate swan
#

help

sick birch
sick birch
slate swan
sick birch
#

Is the version you installed it on the same as the python version?

#

Perhaps try a venv to avoid confusion?

quiet bronze
slate swan
#

@sick birch

sick birch
#

!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 Windows PowerShell, you may need to change the execution policy first. This is only required once:
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser

sick birch
#

Try creating a venv

prisma prism
#

is it against terms of service if My bot is designed to PM a user if/when they receive a warning in a server that they are in?

#

I assumed it wasn't, but just thought i'd find ut

faint mural
#

You are allowed to do that

sick birch
prisma prism
#

ah cool

scarlet linden
#

hey

#
from discord import app_commands
from discord.ext import commands
from discord.ext.commands import has_permissions, MissingPermissions

class aclient(discord.Client):
    def init(self):
        super().init(intents=discord.Intents.default())
        self.synced = False

    async def on_ready():
        print("We have logged in as {self.user}.")
Intents = discord.Intents(messages=True, guilds=True)

client = discord.Client(intents=Intents)
tree = app_commands.CommandTree(client)
@tree.command(name="ban")
@commands.has_permissions(ban_members=True)

async def ban(ctx, member: discord.Member, *, reason: str):
    if reason==None:
      reason=" no reason provided"
    await ctx.channel.send(embed=embed)
    await ctx.guild.ban(member)

embed = discord.Embed(title="Banned Successfully.", description=f"{member} got banned for s", color=discord.Color.random())

client.run("TOKEN")```

error
```Traceback (most recent call last):
  File "main.py", line 26, in <module>
    embed = discord.Embed(title="Banned Successfully.", description=f"{member} got banned for s", color=discord.Color.random())
NameError: name 'member' is not defined```
#

@fading marlin do u know why member is undefined

fading marlin
#

indentation by the looks of it

#

oh what

#

I've seen this code before

scarlet linden
scarlet linden
bright wedge
fading marlin
# scarlet linden how would that affect it

that's basic python. You should pay attention to your indentations
this

a = "a"
b = "b"
if a == "a":
  if b == "b":
    print("a and b are the same")

is not the same as

if a == "a":
  print("a is the same")
if b == "b":
  print("b is the same")
austere vale
#
#delete invite links
@bot.event
async def on_message(message):
  if message.guild is None:
    return
  role =nextcord.utils.find(lambda r: r.name == 'Consigliere', message.guild.roles)
  if role in message.author.roles:
    return
  discordInviteFilter = re.compile("(...)?(?:https?://)?discord(?:(?:app)?\.com/invite|\.gg)/?[a-zA-Z0-9]+/?")
  if discordInviteFilter.match(message.content):
    await message.delete()
  await bot.process_commands(message)

can someone help me with this error?

Ignoring exception in on_message
Traceback (most recent call last):
  File "C:\Users\kouxi\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\client.py", line 502, in _run_event
    await coro(*args, **kwargs)
  File "c:\Users\kouxi\Runa\main.py", line 100, in on_message
    if role in message.author.roles:
AttributeError: 'User' object has no attribute 'roles'
scarlet aurora
#
    @commands.command()
    @commands.has_permissions(manage_messages=True)
    async def role(self, ctx, user: discord.Member, rank):
        addrole = discord.utils.get(ctx.guild.roles, name=rank)
        print(addrole)```How do I get the rank by them only typing the name of the rank in
sick birch
#

If channel is a private channel or the user has the left the guild, then it is a User instead.

austere vale
#

so i gotta change it to a public channel?

sick birch
scarlet linden
#
from discord import app_commands
from discord.ext import commands
from discord.ext.commands import has_permissions, MissingPermissions

class aclient(discord.Client):
    def init(self):
        super().init(intents=discord.Intents.default())
        self.synced = False

    async def on_ready():
        print("We have logged in as {self.user}.")
Intents = discord.Intents(messages=True, guilds=True)

client = discord.Client(intents=Intents)
tree = app_commands.CommandTree(client)
@tree.command(name="ban")
@commands.has_permissions(ban_members=True)

async def ban(ctx, member: discord.Member, *, reason: str):
    if reason==None:
      reason=" no reason provided"
    await ctx.channel.send(embed=embed)
    await ctx.guild.ban(member)

embed = discord.Embed(title="Banned Successfully.", description=f"{member.id} got banned for {reason}", color=discord.Color.random())

client.run("token")```

how would that change the fact that member and reason is undefined
fading marlin
#

because of your scope

scarlet linden
austere vale
#

thank u robin

#

wait, is there a way to change the code and bypass this so that it will take effect whether its public channel or not

scarlet linden
#

wont let me pick certain ones

fading marlin
fading marlin
sick birch
#

There are a few reasons that it's a discord.User:

  • Private channel in a guild
  • User left
  • Message is in a DM channel
#

You can only get .roles if it's in a private channel

austere vale
#

maybe instead of checking if they have a role, i can check if they have admin permissions?

sick birch
#

You could try something like:

try:
  roles = message.author.roles
except:
  # handle error here
slate swan
slate swan
#
class MyView(discord.ui.View):
  def __init__(self):
    super().__init__()
    for i in range(25):
      self.add_item(Button(label=f"{i}"))

how would i make a callback for each one of these buttons?

sick birch
waxen igloo
#

how would i make the bot send a error whenever the wrong grouped sub command is provided

slate swan
#

What is the easiest way to have a user specific cooldown

prisma prism
#

Can someone please help me with discord.py?
I'm trying to send a private message but it just displays the message in chat, not as a PM.

await ctx.send(user, embed=embed2)

here is my code

sick birch
#

so if you use the command in a guild channel it'll send in the same guild channel, if you use it in a DM it'll send in a DM

prisma prism
#

ah ok

#

how do I make it send as DM from wherever

#
await user.send(embed=embed2)
#

Figured it out 🙂

unkempt canyonBOT
#

@little lava Per Rule 6, your invite link has been removed. If you believe this was a mistake, please let staff know!

Our server rules can be found here: https://pythondiscord.com/pages/rules

hollow quarry
#

haha, our bot found your invite link filter :p

#

you can just omit the link and put in a placeholder

little lava
#
import discord
from discord.ext import commands

client = commands.Bot()


@client.event
async def on_ready():
    print("Bot serving contents!")
    await client.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name="Spam Detector"))

@client.event
async def on_message(ctx):
    if ctx.content.startswith("URL"): # Replace URL
        await ctx.delete()
        await ctx.channel.send(f"{ctx.author.mention} Please don't post invite links here!")


client.run("TOKEN")```
#

XD yes i want that

#

code seems ok but the bot not working with <Administrator> permission

slate swan
little lava
slate swan
#

bots most definitely can detect links

little lava
#

is there another method to detect the URL?
other than ctx.content.startswith ?
it seems only detect words.. not URL.

vale wing
#

That's a bit of complex topic, you need to take some tutorials

south coyote
#

is it really possible to merge two json files without getting a brick?

little lava
vale wing
#

You can do it just by replacing last } in first file with , and removing the first { in second file, then merge them

#

Although with this method you might get duplicated keys

#

Or by loading them both and merging with dict.update

#

Not sure why'd you need to do it at all

slate swan
#

my buttons stop working after a few minutes

#

even when the bot is online

#

anyone know why?

scarlet linden
#

@wintry shoal

slate swan
stone field
#

hello, how come this isnt working? @bot.command() async def convert(ctx, message): await ctx.send(f"{message}" / 125)

#

discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: unsupported operand type(s) for /: 'str' and 'int'

slate swan
#

because u are trying to divide and int and str

stone field
slate swan
#

learn python basics

stone field
#

thanks i really appreciate the help in the python help server

slate swan
#

we are here to help not spoon feed code

#

this is also the discord bots help channel and ur issue lies within the basics of python not a didscord bot

stone field
slate swan
stone field
#

yeah ik now lol, i figured it out

slate swan
slate swan
slate swan
#

Yes, but since it's a simple error it tells me that you don't know basic python

stone field
stone field
slate swan
#

🤓

slate swan
#

💀🤓

#

This kid I swear

slate swan
#

They will do everything but learn python

stone field
#

idc how complex it is as long is works

slate swan
slate swan
slate swan
#

yes you do?

slate swan
#

how do you expect the lib to find the button lol

stone field
slate swan
#

i haven't gotten any error without the custom_id

#

i'll add a custom id if i come upon a bug

slate swan
#

!resources

unkempt canyonBOT
#
Resources

The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.

slate swan
#

Here now this is how you learn python

slate swan
#

relax guys

slate swan
# stone field you're*

Ok? Cool but that still doesn't prove my point of you not learning something and just copy and pasting

slate swan
slate swan
stone field
slate swan
#

Google won't get you a job bro 💀

stone field
#

i dont need a job

slate swan
#

@stone field
what's a float?

#

💀

stone field
slate swan
#

ur a 12 year old on fortnite trolling. ima block u.

slate swan
stone field
slate swan
#

bro 💀

slate swan
stone field
slate swan
#

go play roblox

slate swan
rugged shadow
#

how ironic

slate swan
rugged shadow
#

yea

#

he be on that shi

slate swan
rugged shadow
#

anyway

#

@slate swan mind telling me if you know what a float is? lmao

#

maybe if you told a potentially new coder what they were trying to do with the code instead of just "learn python basics"

shrewd apex
slate swan
#

this also isn't the place for "new coders" you shouldn't be creating discord bots if you are a "new coder"

#

can you show your actual code logic.

#

from what u pasted its out of order

#

and confusing

#

yea you are iterating through data and assigning values then you exit the for statement without adding the values to the embed so the last iteration is what is used

#

mmh

#

and how can I change that?

#

you need to add the embed fields in your first for statement

#

you are also duplicating code

#

you can just

embed.add_field(name=retailer['retailer']['retailler_name'], value=....)
#

and request are blocking. aiohttp would better suit you

slate swan
#

u don't define it anywhere

maiden fable
#

Seems like come is a dict, not a list/tuple

jagged widget
#

there is no error but bot is not replying

paper sluice
#

its channel.send not channel.sent

upbeat gust
#

Using dpy 2.0 and not getting any errors? This is on purpose, the library now uses logging to send errors but only if you're using Client/Bot.run. More about that in ?tag defaultlogging.

It's recommended to setup logging yourself if you aren't using .run or use the utils.setup_logging helper function: just put discord.utils.setup_logging() anywhere in your running file. Docs: https://discordpy.readthedocs.io/en/stable/api.html#discord.utils.setup_logging

but I can't use Client/Bot.run!
You can! You can load cogs and do other stuff in the newly added setup_hook method that is called once after the bot logs in, more about that and how to implement it in ?tag setuphook.

upbeat gust
slate swan
#

yee

pearl fjord
#

real helpful, mr "events team" member

#

it was because there was a typo in the word "attachments"

primal token
#

Bones doesnt know everything? They're just experienced and have there own life and things to do

pearl fjord
#

it would seem

#

took me 2 hours to see the typo

primal token
#

No? it should be "doesn't"?

primal token
pearl fjord
#

"staff don't know everything" not "staff doesn't know everything"

primal token
#

Now i specified their name, now its correct, no?

pearl fjord
#

it would be if it was "doesn't"

primal token
#

Either way lets not be pedantic and flood the chat

primal token
#

You forgot to correct my punctuation.

pearl fjord
#

one thing at a time lad

primal token
#

One thing at a time lad.*

#

😎

velvet compass
#

Let's stop whatever this is

primal token
#

yes

pearl fjord
primal token
#

!ot

unkempt canyonBOT
pearl fjord
#

HAHHAHAHAHA

velvet compass
pearl fjord
#

Halloween

#

cool

#

i get a pumpkin

#

a discord bot related pumpkin

vocal snow
#

why cursor = await cursor.execute(...)?

#

are you sure it returns the cursor? Or does it return the query status code

slate swan
bitter jewel
#
    async def whitelist(ctx, user: discord.Member=None):
  File "D:\etc\devv\bilenatorul\main.py", line 45, in check_whitelist
    if str(ctx.author.id) in f.read():
AttributeError: 'function' object has no attribute 'author'```

```py
def check_whitelist(ctx):
    with open('users.txt') as f: 
        if str(ctx.author.id) in f.read():
            return ctx.author.id

@bot.command()
@bot.check(check_whitelist)
async def whitelist(ctx, user: discord.Member=None):
    if user == None:
        await ctx.send("Ai uitat sa mentionezi persoana sau id-ul.")
        return

    def whitelisted(user_id): 
        with open('users.txt', 'r') as f:
            if str(user_id) in f.read():
                return True
            else:
                return False

    def addwhitelist(user_id):
        with open('users.txt', 'a') as f: 
            f.write(f"{str(user_id)}\n")
            f.close()

    if whitelisted(user.id) == True:
        await ctx.send(f"{user} este deja in lista de useri.")
    else:
        addwhitelist(user.id)
        await ctx.send(f"{user} a primit acces la comenzi.")

unkempt canyonBOT
#

Hey @slate swan!

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

vocal snow
#

Did you not understand the error pithink

#

Read the last line of the error

#

You're trying to convert that string to an int

#

Like doing int("abc") which makes no sense

#

get_channel needs a channel id

#

You need to figure out where you're storing that

#

Yes but where in the tuple

#

You're selecting msg, channelID

#

So your tuple will also be (msg, channelID)

#

Nonononon

#

Don't do that lmaoo

#

Go back to your old code

#

You already have the channel id

#

It's the second item in the tuple

#

So just use come[1] instead

#

In python you can access elements of a tuple and list with their index, starting from 0

#

!e ```py
data = ("message", 12345)
print(data[0])
print(data[1])

unkempt canyonBOT
#

@vocal snow :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | message
002 | 12345
lucid galleon
#

why i am getting this error? RuntimeError: Event loop is closed

vocal snow
#

Can you send the full traceback?

lucid galleon
#

@vocal snow how to send full traceback?

dull terrace
#

Should be zero because you'll have one result

#

But if it's saying key error that means it has zero results for that guild and you need to make sure the channel ID is saved for that guild

#

If there are no results for that guild id itll return None

honest laurel
#

@slate swan Learn how to debug, even simple print(come) would work 😉

#

Well, it would be better if you check what your variable actually contains

honest laurel
#

{'msg': '%member hello', 'channelID': 1013088096633499708} your variable clearly does not have 0 or 1 keys

honest laurel
slate swan
#

hello, has anyone got an example for slash commands with the new discord 2.0

lucid galleon
honest laurel
#

Can you share full traceback?

lucid galleon
honest laurel
lucid galleon
honest laurel
#

It depends

#

Learn how to use dictionaries

vocal snow
#

no, you need to learn to use dictionaries

#

it's already a dict, why are you casting it to a dict

lucid galleon
# honest laurel It depends
TOKEN =""

intents = discord.Intents.default()
intents.message_content = True

client = discord.Client(intents=intents)

@client.event
async def on_connect():
    print(f'We have logged in as {client.user}')

@client.event
async def on_message(message):
    if message.author == client.user:
        return

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


client.run(TOKEN)
little lava
honest laurel
vocal snow
lucid galleon
# lucid galleon ``` TOKEN ="" intents = discord.Intents.default() intents.message_content = Tru...

Traceback (most recent call last):
  File "F:\discord bot\bot.py", line 32, in <module>
    client.run(TOKEN)
  File "F:\pyenv\lib\site-packages\discord\client.py", line 828, in run
    asyncio.run(runner())
  File "F:\pyenv\lib\asyncio\runners.py", line 44, in run
    return loop.run_until_complete(main)
  File "F:\pyenv\lib\asyncio\base_events.py", line 647, in run_until_complete
    return future.result()
  File "F:\pyenv\lib\site-packages\discord\client.py", line 817, in runner
    await self.start(token, reconnect=reconnect)
  File "F:\pyenv\lib\site-packages\discord\client.py", line 745, in start
    await self.login(token)
  File "F:\pyenv\lib\site-packages\discord\client.py", line 580, in login
    data = await self.http.static_login(token)
  File "F:\pyenv\lib\site-packages\discord\http.py", line 805, in static_login
    raise LoginFailure('Improper token has been passed.') from exc
discord.errors.LoginFailure: Improper token has been passed.
Exception ignored in: <function _ProactorBasePipeTransport.__del__ at 0x000001CE8B9E71F0>
Traceback (most recent call last):
  File "F:\pyenv\lib\asyncio\proactor_events.py", line 116, in __del__
    self.close()
  File "F:\pyenv\lib\asyncio\proactor_events.py", line 108, in close
    self._loop.call_soon(self._call_connection_lost, None)
  File "F:\pyenv\lib\asyncio\base_events.py", line 751, in call_soon
    self._check_closed()
  File "F:\pyenv\lib\asyncio\base_events.py", line 515, in _check_closed
    raise RuntimeError('Event loop is closed')
RuntimeError: Event loop is closed
honest laurel
#

Your token is not valid

lucid galleon
#

Ok

#

Reset my token but it still showing me error ```
Traceback (most recent call last):
File "F:\discord bot\bot.py", line 32, in <module>
client.run(TOKEN)
File "F:\pyenv\lib\site-packages\discord\client.py", line 828, in run
asyncio.run(runner())
File "F:\pyenv\lib\asyncio\runners.py", line 44, in run
return loop.run_until_complete(main)
File "F:\pyenv\lib\asyncio\base_events.py", line 647, in run_until_complete
return future.result()
File "F:\pyenv\lib\site-packages\discord\client.py", line 817, in runner
await self.start(token, reconnect=reconnect)
File "F:\pyenv\lib\site-packages\discord\client.py", line 746, in start
await self.connect(reconnect=reconnect)
File "F:\pyenv\lib\site-packages\discord\client.py", line 672, in connect
raise PrivilegedIntentsRequired(exc.shard_id) from None
discord.errors.PrivilegedIntentsRequired: Shard ID None is requesting privileged intents that have not been explicitly enabled in the
developer portal. It is recommended to go to https://discord.com/developers/applications/ and explicitly enable the privileged intents within your application's page. If this is not possible, then consider disabling the privileged intents instead.
Exception ignored in: <function _ProactorBasePipeTransport.del at 0x00000235D16B71F0>
Traceback (most recent call last):
File "F:\pyenv\lib\asyncio\proactor_events.py", line 116, in del
self.close()
File "F:\pyenv\lib\asyncio\proactor_events.py", line 108, in close
self._loop.call_soon(self._call_connection_lost, None)
File "F:\pyenv\lib\asyncio\base_events.py", line 751, in call_soon
self._check_closed()
File "F:\pyenv\lib\asyncio\base_events.py", line 515, in _check_closed
raise RuntimeError('Event loop is closed')
RuntimeError: Event loop is closed

#

what to do?

honest laurel
#
discord.errors.PrivilegedIntentsRequired: Shard ID None is requesting privileged intents that have not been explicitly enabled in the 
developer portal. It is recommended to go to https://discord.com/developers/applications/ and explicitly enable the privileged intents within your application's page. If this is not possible, then consider disabling the privileged intents instead.
little lava
#

This is a bot that detect the URLs and remove URLs then finally send warning to the text channel.

it does not show any errors and not even detecting a word.

any advises?

cloud dawn
#

The user most likely used the all function on the intents object

vocal snow
honest laurel
lucid galleon
#

I enabled it as given in docs but it isn't working. Same error

honest laurel
#

intents.message_content = True But you don't have message content intent enabled

lucid galleon
#

It's working. Thanks

cloud dawn
#

I also recommend setting the right event policy no one wants to see event loop closed on every error lol

honest laurel
little lava
honest laurel
stone field
#

hi, how do i make it say the entire message and not just the first word?

#
async def say(ctx, message):
    if message == "@everyone":
        await ctx.send("Nice try buddy")
        return
    if message == "@here":
        await ctx.send("Nice try buddy")
        return
    await ctx.send(message)```
stone field
#

okay let me try that

#

perfect tyvm

stone field
# sick birch Use ctx, *, message

how would i make it so that it reads 2 inputs? ik this probably isnt right but i put message2 to kinda make sense of what im trynna askasync def remind(ctx, *, message): await ctx.send(f"Reminding you about `{message}` in {message2} seconds.")

bitter jewel
#
  File "D:\etc\devv\bilenatorul\main.py", line 50, in <module>
    async def whitelist(ctx, user: discord.Member=None):
  File "D:\etc\devv\bilenatorul\main.py", line 45, in check_whitelist
    if str(ctx.author.id) in f.read():
AttributeError: 'function' object has no attribute 'author'
def check_whitelist(ctx):
    with open('users.txt') as f: 
        if str(ctx.author.id) in f.read():
            return ctx.author.id

@bot.command()
@bot.check(check_whitelist)
async def whitelist(ctx, user: discord.Member=None):
    if user == None:
        await ctx.send("Ai uitat sa mentionezi persoana sau id-ul.")
        return

    def whitelisted(user_id): 
        with open('users.txt', 'r') as f:
            if str(user_id) in f.read():
                return True
            else:
                return False

    def addwhitelist(user_id):
        with open('users.txt', 'a') as f: 
            f.write(f"{str(user_id)}\n")
            f.close()

    if whitelisted(user.id) == True:
        await ctx.send(f"{user} este deja in lista de useri.")
    else:
        addwhitelist(user.id)
        await ctx.send(f"{user} a primit acces la comenzi.")
#

ig nobody got idea whats happening

vocal snow
#

you're passing a function to check_whitelist

#

where are you calling check_whitelist pithink

stone field
vocal snow
#
async def remind(ctx, time: int, *, message: str):
    ...
stone field
#

so for example if i typed "$remind feed cat 600" and i want it to respond "Reminding you about feed cat in 600 seconds" how would i do that

#

@vocal snow

vocal snow
#

I wouldn't recommend doing this since parsing this is harder than just taking the seconds first

stone field
vocal snow
#

no, you do $remind 600 feed cat

stone field
#

yeah

vocal snow
#

or you could do $remind "feed cat" 600

stone field
#

how would i make it sleep for 600 seconds though

#

then do the await ctx.send

bitter jewel
vocal snow
#

!d asyncio.sleep

unkempt canyonBOT
#

coroutine asyncio.sleep(delay, result=None)```
Block for *delay* seconds.

If *result* is provided, it is returned to the caller when the coroutine completes.

`sleep()` always suspends the current task, allowing other tasks to run.

Setting the delay to 0 provides an optimized path to allow other tasks to run. This can be used by long-running functions to avoid blocking the event loop for the full duration of the function call.

Deprecated since version 3.8, removed in version 3.10: The `loop` parameter. This function has been implicitly getting the current running loop since 3.7. See [What’s New in 3.10’s Removed section](https://docs.python.org/3/whatsnew/3.10.html#whatsnew310-removed) for more information.

Example of coroutine displaying the current date every second for 5 seconds:
vocal snow
#

but that's not how you use it

#

you want it to be a global check right?

#

it should apply to all commands

bitter jewel
#

no

#

just to that one

vocal snow
#

then you should use discord.ext.commands.check

bitter jewel
#

like @bot.discord.ext.commands.check?

vocal snow
#

no

#
from discord.ext import commands

@bot.command()
@commands.check(...)
...
vocal snow
#

yeah so now use @commands.check(check_whitelist)

#

not @bot.check

simple kettle
#

Why do discord bots need message content intents to respond to commands?

vocal snow
hushed galleon
#

discord does provide content to bots for DMs and messages that mention them, so you're not completely ruined if you dont have the intent

cloud dawn
#

Anyone has a good button interaction paginator? I uhm yes.

hushed galleon
#

i wrote one as part of my bot, and tbf i should probably turn it into a package eventually

simple kettle
#

Alright thanks y’all I need to verify my bot and it’s asking why I need it

vocal snow
simple kettle
#

I’m not sure how to do slash commands

hushed galleon
#

unfortunately they wont accept "text commands" as a reason for getting message content iirc

vocal snow
#

they won't give you message content intents if you don't have a valid reason (and text commands aren't a valid reason unfortunately)

vocal snow
simple kettle
#

Yeah

#

That’s so dumb tho

vocal snow
#

the latest version?

simple kettle
#

Nope

cloud dawn
vocal snow
#

yeah thats what i mean

#

anything after 1.7.3

cloud dawn
simple kettle
#

Won’t I have to change almost all my code?

vocal snow
#

not really

simple kettle
#

How do you make slash commands

simple kettle
#

Ok I guess that does not look too bad

vocal snow
#

for the other changes

simple kettle
#

So I’m a little confused will I not be able to have text commands

vocal snow
#

no, only app commands like slash commands or context menus

simple kettle
#

Cause I still want that so I need message content intent

cloud dawn
simple kettle
#

That’s crazy

vocal snow
#

it's for privacy reasons

cloud dawn
simple kettle
#

So should I remove text commands?

cloud dawn
#

If you want a public bot, yes.

simple kettle
#

Dang ok

hushed galleon
#

i havent made the buttons customizable either but you can edit the source/subclass if you want that

cloud dawn
#

🡺 I like these navigation arrows :3

hushed galleon
#

if you know of the older discord-ext-menus package (reaction-based) it works somewhat similarly with different sources you can use

simple kettle
vocal snow
#

there is a Context.from_interaction i think

#

!d discord.ext.commands.Context.from_interaction

unkempt canyonBOT
#

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

Creates a context from a [`discord.Interaction`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction "discord.Interaction"). This only works on application command based interactions, such as slash commands or context menus.

On slash command based interactions this creates a synthetic [`Message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message "discord.Message") that points to an ephemeral message that the command invoker has executed. This means that [`Context.author`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Context.author "discord.ext.commands.Context.author") returns the member that invoked the command.

In a message context menu based interaction, the [`Context.message`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Context.message "discord.ext.commands.Context.message") attribute is the message that the command is being executed on. This means that [`Context.author`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Context.author "discord.ext.commands.Context.author") returns the author of the message being targetted. To get the member that invoked the command then [`discord.Interaction.user`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction.user "discord.Interaction.user") should be used instead.

New in version 2.0.
simple kettle
#

Alright thanks

#

Is version 2.0 official?

vocal snow
#

it's stable, yes

cloud dawn
#

I've already got a list of embeds passing them is pure pain.

slate swan
#

help me make a nuker

#

😁

#

but restores all channels on 1 command

cloud dawn
hushed galleon
#

you'll see the subclassed page sources inside my two examples

cloud dawn
hushed galleon
#

for the regular "pagination" usage you only need one ListPageSource in your case

#

there's two features to it, one is pagination and the other is navigation

#

navigation allows PageSources to return other PageSources, and when the user navigates to one of those sources it's added onto the PaginatorView.sources stack

#

aka nested pages

cloud dawn
#

I tried using ListPageSource but I need to define page_size but embeds don't have a page size.

hushed galleon
#

oh right, its meant to take a list of stuff and then chunk it into sublists for format_page to format it as an embed

cloud dawn
#

So it is text based 😂

hushed galleon
#

wdym

cloud dawn
#

I can't pass embeds I need to pass text and use format_page to make the embed.

hushed galleon
#

you can pass anything you want in the list

cloud dawn
#

But not a list of Embeds.

hushed galleon
#

sure you can

cloud dawn
#

Then I'm doing something very wrong.

hushed galleon
#

it can be as simple as this: ```py
class PassThroughPageSource(
ListPageSource[discord.Embed, None, PaginatorView]
): # list[E] S V
# first one specifies the type of each element
# in the list
def init(self, embeds: list[discord.Embed]):
super().init(embeds, page_size=1)

def format_page(self, view: PaginatorView, page: list[discord.Embed]):
    return page[0]

Usage:

view = PaginatorView(sources=PassThroughPageSource(embed_list))
await view.start(inter_or_channel)```

rigid hare
#

before i give myself a headache trying in vain,,

#

is it possible to load a cog, from within a cog?

hushed galleon
#

yes, although thats not a common use case

slate swan
hushed galleon
#

personally for my multi-cog extensions i use setup() to load the cogs

cloud dawn
rigid hare
#

im working remotely, and just because i know for a fact i'd lose an SSH session somehwere, im running the bot on tty2 for ease of use sake, and i don't wanna have to go and VNC into my KVM in the event that i want to add a cog in the future

hollow badger
rigid hare
#

so i was just going to have a skeleton main.py with a reload command, that reloads a main cog where i actually set up all my cogs and keep everything organised

#

does it react to anything with skeleton in it? lmao

hushed galleon
rigid hare
#

guess so hahaha

slate swan
hollow badger
#

I don't care.

rigid hare
hushed galleon
#

cogs and extensions are very different

cloud dawn
hushed galleon
#

extensions allow code to be hot-reloaded, while cogs are merely how you organize listeners/commands together

hollow badger
# slate swan I'm matching his energy

If you have a problem with another member you have several options:

  • ignore them
  • block them
  • report them via ModMail
  • any/all of the above

You do not need to cause further disruption by "matching their energy".

The same applies to everyone.

hushed galleon
#

adding generic types for it has been quite confusing to do

cloud dawn
worn pumice
#

!resources

unkempt canyonBOT
#
Resources

The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.

mental hollow
#

I know this would work for prefixed commands but would this work for slash like shown below?

access = [836895718563250196, 831118106876969021]
@bot.event
async def on_message(ctx: discord.ApplicationContext, message: discord.Message):
    if not ctx.author.id in access:
        return await ctx.respond("Only a few people have access to this bot. Kindly use @MusicBot")
    else:
        pass
    await bot.process_commands(message)
shrewd apex
#

slash commands dont send a message do they it triggers a webhook iirc

mental hollow
#

really?

split nest
#

is there a way that a bot can recognize voices

cloud dawn
obtuse blaze
#

!paste

#

code is kinda rly bad atm could anyone give me opinion on how to improve + it has a lot of flaws but idk how to make it another way

cursive spindle
#

is there anyway to make a python program for run 3-4 bots, i mean the program run the same code for theses 4 bots.

#

all this one loop

shrewd apex
#

altho i dont see the use case

shrewd apex
# obtuse blaze !paste

u could use a single db connection instance through ur bot instead of making multiple connections over the code

lucid galleon
#

it is not working but why?@bot.command(name="ping") async def test_msg(ctx): await ctx.send("pong")