#discord-bots

1 messages · Page 109 of 1

verbal monolith
#

robin. ive spent the past 5 hours making this terrible bot. i will do whatever it takes

sick birch
#

maybe do something like that. create a private channel you can use the say command on that'll relay your messages somewhere else

sick birch
#

You might be able to combine run in executor and stdin or some other solution, or just use aioconsole

verbal monolith
#

alr

#

but this is for tomorrow

#

its 3am, thank you both alot btw yall helped alot <3

#

gn

sick birch
#

night

hushed galleon
#

last time i used await asyncio.to_thread(input) in one of my library examples it worked pretty well, though stuff tended to print in the way

south coyote
#

hey guys

#

im looking to incorporate a tip bot in my discord

#

i have the official github for the chain my token is built on and they have a tipbot but im wondering if it is viable

#

can anybody help me take a look?

glad cradle
vale wing
#

Same, prolly private repo

south coyote
#

nevermind i think its in javascript

silent portal
#

it's because of your "try"

#

try removing it and see if you get any errors

slate swan
#

moving to discord classic before they remove it Run

austere vale
#

does anyone know any common causes of why my aiosqlite databases keep resetting randomly? i dont wanna send the entire file of hundreds of lines of code, so many someone knows common errors? i have self.bot.db.commit() whenever i change data values, but it keeps resetting every so often

vocal snow
austere vale
#

so i guess its deleting the data?

vocal snow
#

If it's setting it to 0 then that's an UPDATE

#

You'll need to check your code for the places you're updating that data

silent portal
#

Yo, I'm trying to make a select menu that has every member in the interaction.user.voice.channel, I know I can loop trough them and append them on a list and stuff, but I don't know how to access that list from the view class, can someone help me with that?

amber ether
#

``js

issubclass() arg 1 must be a class`` bu

#

What does that mean im switching

#

slash

slate swan
#

!d issubclass

unkempt canyonBOT
#

issubclass(class, classinfo)```
Return `True` if *class* is a subclass (direct, indirect, or [virtual](https://docs.python.org/3/glossary.html#term-abstract-base-class)) of *classinfo*. A class is considered a subclass of itself. *classinfo* may be a tuple of class objects (or recursively, other such tuples) or a [Union Type](https://docs.python.org/3/library/stdtypes.html#types-union), in which case return `True` if *class* is a subclass of any entry in *classinfo*. In any other case, a [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "TypeError") exception is raised.

Changed in version 3.10: *classinfo* can be a [Union Type](https://docs.python.org/3/library/stdtypes.html#types-union).
slate swan
#

it takes 2 args

amber ether
#

i should has used int

#

Anyone wtf?

slate swan
paper sluice
#

put them inside strings, # makes a comment

slate swan
#

you can do 0xFFFFFF like this

paper sluice
#

0*

amber ether
slate swan
#

yes

amber ether
#

so that will fiox sintax?

slate swan
#

yep

amber ether
#

Arigato!

#

Application Command raised an exception: AttributeError: module 'cloudscraper' has no attribute 'get' I love Cloudscraper

slate swan
#

pls help here

unkempt canyonBOT
#

Please provide the full traceback for your exception in order to help us identify your issue.
While the last line of the error message tells us what kind of error you got,
the full traceback will tell us which line, and other critical information to solve your problem.
Please avoid screenshots so we can copy and paste parts of the message.

A full traceback could look like:

Traceback (most recent call last):
  File "my_file.py", line 5, in <module>
    add_three("6")
  File "my_file.py", line 2, in add_three
    a = num + 3
TypeError: can only concatenate str (not "int") to str

If the traceback is long, use our pastebin.

empty quest
paper sluice
#

they do

slate swan
#

my sister's first attempt at her own bot

#
import discord
import os
from discord import Intents

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

client = discord.Client(intents=intents)

@client.event
async def on_ready():
  print("We have logged in as {0.user}".format(client))

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

  if message.content.startswith("'snipe"):
    await message.channel.send("You shoot a sniper rifle!")

client.run(os.getenv("TOKEN"))
verbal monolith
#

shouldnt it be client.run('TOKEN')?

slate swan
#

idk why

verbal monolith
#

for my bot i did this

cobalt relic
#

Not sure where to post this but it’s for a discord bot so I’ll post here:

What is a good way to display a graph in an image? I’m looking for a simple timeline graph using the curvy lines not straight ones (sorry I know that’s a bad explanation)

I’ve looked into matplotlib but it’s just not very aesthetically pleasing. (Though maybe there is stuff I don’t know about customization with it, I don’t know much about the library)

#

use guild.owner

slate swan
cobalt relic
slate swan
cobalt relic
spice scroll
#

i've tried
pip install discord.py
and
py -3 -m pip install -U discord.py

glad cradle
#

are you getting a pip error?

spice scroll
#

yes

glad cradle
#

show it

#

!paste

unkempt canyonBOT
#

Pasting large amounts of code

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

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

spice scroll
#
operable program or batch file.
#

and the bottom one runs it but when I try to import discord in my IDE it errors as well

glad cradle
#

is your python path in your system environmental variables?

spice scroll
#

i think so? idk

#

you mean directory?

glad cradle
#

when you install python you can add the python path to PATH (that is an system environmental variable that contains various paths) have you selected that option at installation?

spice scroll
#

i did, i specified the path it was in and ran that command. same error

slate swan
#

Code:

import discord

TOKEN = "token"

client = discord.Client()

@client.event
async def on_ready():
    print("{0.user} is now online!".format(client))

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


client.run(TOKEN)```

Error:
```py
File "/home/container/bot.py", line 5, in <module>
    client = discord.Client()
TypeError: __init__() missing 1 required keyword-only argument: 'intents'```
glad cradle
#

!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. By default discord.py has all intents enabled except for Members, Message Content, and Presences. These are needed for features such as on_member events, to get access to message content, and to get members' statuses.

To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.

Next, in your bot 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

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

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

For more info about using intents, see the discord.py docs on intents, and for general information about them, see the Discord developer documentation on intents.

slate swan
#

Your local version of discord.py may be outdated, make sure you're on the latest version

silent portal
#

Yo, I'm trying to make a select menu that has every member in the interaction.user.voice.channel, I know I can loop trough them and append them on a list and stuff, but I don't know how to access that list from the view class, can someone help me with that?

slate swan
#

If your host gives the error, it's on a newer version

#

If you don't get the error locally, you're using an old version on your PC

slate swan
#

Simply update the package with pip

#

these are the packages from host

#

Yes, and that's the latest - by the way, you only need discord.py 2.0.1

#

Your host is fine as I said.

#

Your local installation is outdated if you don't get the error

#

A host is not local

#

is it in site packages folder?

#

As I said, simply update it via pip

#

You don't need to look for folders, just update.

#

That won't update it, no

#

Search engines are your friend

python -m pip install -U discord.py
#

In that case you will get the error when running with python file.py

#

no

#

its not giving me an error

#

Well first of all, why on earth do you define client twice

#

nothing shows up

#

Yeah I don't think py and python is the same command, or is it on windows?

slate swan
#

You only need discord.py

slate swan
#

pip uninstall discord

slate swan
#

What if you use python file.py

#

i removed the client that was defined 2x

slate swan
slate swan
slate swan
#

imma try

#

About if there is a difference when using python file.py and using py file.py

#

Because you seem to be double clicking the file

#

nope not a difference at all

#

Well either way you have the intents defined now

#

It is required for 2.0 and above

#

im trying on the server rn

#
  File "/home/container/bot.py", line 1, in <module>
    import discord
ModuleNotFoundError: No module named 'discord'```
#
import discord

TOKEN = ""

client = discord.Client()

@client.event
async def on_ready():
    print("{0.user} is now online!".format(client))

client.run(TOKEN)```
#

Well you still need to install discord.py..

#

did

#

And you're missing the intents again

slate swan
#

Having it listed there doesn't mean the hosting provider necessarily installs it

slate swan
#

im taking other code

vale wing
#

Bad code

slate swan
#

my head is getting fkd

vale wing
#

It's bad just because it has a command in on_message

slate swan
#

im trying here for hours

#

i just want a code to set my bot online nothing more

vale wing
#

What exactly do you need to implement, what is your knowledge level and what tutorials/articles have you read so far

vale wing
slate swan
#

no commands or anything just online status

gilded fern
#

anyone what is a mistake here i am trying for first time

vale wing
#

You are probably having issues with running it aren't you

vale wing
vale wing
vale wing
slate swan
vale wing
#

Basic python indents

vale wing
vale wing
#

If you were a bit of more experienced you'd easily understand this

#

So I recommend learning python first to receive help quickly without people spending time on you to explain basic things

gilded fern
gilded fern
vale wing
#

There was a nice message explaining why you shouldn't begin to learn python without previous coding experience from a discord bot

vale wing
gilded fern
#

thanks for ur advice

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
#

i just wanna run it so that my bot is online

vale wing
#

On what machine and what environment

vale wing
slate swan
#

no i mean my answer

#

on wrong question

vale wing
#

Because I've seen you attaching some screenshots of weird hosting

vale wing
#

Are there any instructions on how to use it and have you read & understand them

#

Also use a VPS if you aren't looking for free service (there are free tier VPSs too tho)

slate swan
slate swan
vale wing
#

Is it paid

vale wing
slate swan
#

how can it have problems

#

do u got a code to set a bot online

#

i dont rlly want anything mo

#

If the hosting provider is unreliable, you can have the best code it won't change a single thing

slate swan
#

One what?

#

nvm

#
import discord

TOKEN = ""

client = discord.Client()

client.run(TOKEN)```
#

Changing code won't help at all if the hosting provider doesn't install the dependencies correctly

cloud dawn
#
__import__(discord).Client().run("")
``` I like your thinking.
slate swan
#

could use walrus mb

#
(d:=__import__("discord")).Client(intents=d.Intents.default()).run("")
spring needle
#

How to get user id of user who send the command?

slate swan
#

ctx.author.id

spring needle
cloud dawn
slate swan
#

You just need ctx.author.id to get the ID of the user

cloud dawn
#

interaction.author.id for slash tough.

#

yw

spring needle
cloud dawn
slate swan
#

yoikes

cloud dawn
#

!d discord.ext.commands.Context

unkempt canyonBOT
#
class discord.ext.commands.Context(*, message, bot, view, args=..., kwargs=..., prefix=None, command=None, invoked_with=None, invoked_parents=..., invoked_subcommand=None, ...)```
Represents the context in which a command is being invoked under.

This class contains a lot of meta data to help you understand more about the invocation context. This class is not created manually and is instead passed around to commands as the first parameter.

This class implements the [`Messageable`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Messageable "discord.abc.Messageable") ABC.
slate swan
#

ah it's in commands whatever

spring needle
#

Let me find it

slate swan
#

There you have the author attribute that reflects a union

cloud dawn
#

Pretty bad I know that from the top of my head.

slate swan
#

When going on the class for these you see a id attribute

#

Which reflects ctx.author.id when put together

spring needle
#

Ok

slate swan
#

Or if you type hint your code correctly

#

You should get intellisense in your IDE/text editor

#

Which then should show author when you write ctx.

cloud dawn
#

Also in the doc always search by object name not by object path.

#

E.g if I want to search author.id then I'd search for either a User or a Member object with the objects that I've got. This case being ctx aka Context.

#

Well the send only contains a string pithink

#

file is grey so unused.

verbal monolith
#
    if message.content.lower() == 'cum':
        await message.channel.send('ew, you disgusting bitch')
        return
    if message.author.id in USER_IDS:
        response = [f'shut up, {username}', 'be quiet.', 'shush.']
        await message.channel.send(random.choice(response))
    if message.author.id == 951975771730235465:
        response = [f'shut up, {username}']
        await message.channel.send(random.choice(response))```
#

why does it send 3 messages?

maiden fable
#

add a return in each statement, prolly all 3 are being triggered

slate swan
#

The message contains the word you wrote, the message was sent by the user that has the ID in USER_IDS and the message was sent by the user with ID 951975771730235465

#

Hence all of the if statements are true and will get executed

slate swan
#

Add return statements as said above or use if elif elif

verbal monolith
#

it still sends 3

maiden fable
#

Ikr

verbal monolith
# dull terrace <a:thinking_vibrate:585955892252639244>
C:\Users\pellp\testing\Scripts\python.exe "C:\Users\pellp\PycharmProjects\testing\A Very Nice Discord Bot.py" 
  File "C:\Users\pellp\PycharmProjects\testing\A Very Nice Discord Bot.py", line 45
    else message.author.id == 951975771730235465:
         ^^^^^^^
SyntaxError: expected ':'```
dull terrace
#

!e

a, b = True, True
if a:
  print("an")
if b:
  print("example")

print("new test")

if a:
  print("an")
elif b:
  print("example")
unkempt canyonBOT
#

@dull terrace :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | an
002 | example
003 | new test
004 | an
dull terrace
#

...

#

else can't have comparisons or anything

#

you do if then if you need another comparison you do elif and if you want something where if none of the previous things are true you do else on it's own

verbal monolith
#
if message.content.lower() == 'cum':
        await message.channel.send('ew, you disgusting bitch')
    elif message.author.id in USER_IDS:
        response = [f'shut up, {username}', 'be quiet.', 'shush.']
        await message.channel.send(random.choice(response))
    elif message.author.id == 951975771730235465:
        response = [f'shut up, {username}']
        await message.channel.send(random.choice(response))```
slate swan
#

Well, see how your bot responded to "You talk utter..."

#

Which is not in your code sent

#

So there is another event, most likely another on_message, getting triggered

dull terrace
#

what's the word im looking for instead of comparison?

verbal monolith
#

oh my fod

verbal monolith
slate swan
#

All good, happens to everyone KEKW

verbal monolith
#

nvm

#

its still trip messagin

#

heLP

slate swan
#

Check for other events in that case

verbal monolith
#
import discord
from discord.ext import commands
import random

TOKEN = 'gay'

intents = discord.Intents.default()
intents.message_content = True
client = commands.Bot(command_prefix='!', intents=intents)


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


@client.event
async def on_message(message):
    USER_IDS = {879004139361816596, 839883479759585330}  # IDs stored in a set
    username = str(message.author).split('#')[0]
    user_message = str(message.content)
    channel = str(message.channel.name)
    print(f'{username}: {user_message} ({channel}')

    if message.author == client.user:
        return

    if message.channel.name == 'alabama' or message.channel.name == 'ai':
        if message.content.lower() == 'hello' or message.content.lower() == 'hi':
            await message.channel.send(f'hello, {username}!')
            return
        elif message.content.lower() == 'bye':
            await message.channel.send(f'see ya, {username}!')
            return
        elif message.content.lower() == '!random':
            response = f'this is your random number: {random.randrange(100000000000)}'
            await message.channel.send(response)
            return

    if message.content.lower() == 'g':
        await message.channel.send('ew, you disgusting g')
    elif message.author.id in USER_IDS:
        response = [f'shut up, {username}', 'be quiet.', 'shush.']
        await message.channel.send(random.choice(response))
    elif message.author.id == 951975771730235465:
        response = [f'shut up, {username}']
        await message.channel.send(random.choice(response))


client.run(TOKEN)
#

thats the code

#

idk whats up so

#

it was working befere but now it isnt

slate swan
#

Maybe you want to remove the slurs

velvet compass
slate swan
#

And send it without

verbal monolith
#

Oh shit m

#

mb

verbal monolith
#

there is none

dull terrace
#

edge bot

slate swan
#

Slurs are the same as questionable words

#

Which you have more than a few in the snippet

verbal monolith
#

oh

velvet compass
verbal monolith
#

done 👍

velvet compass
#

Thanks. Take care not to post similar things in the future

verbal monolith
#

didnt know bitch, etc was banned here

velvet compass
#

Cursing in general isn't but up to a point. When it is directed at someone it crosses a line

verbal monolith
#

kk

#

anywho, how would i fix it ?

honest shoal
slate swan
#

Yes

#

But not everyone will be guaranteed to get access to it

honest shoal
#

discord will take commission

maiden fable
#

Yea

slate swan
#

pretty obvious

maiden fable
#

Reasons Discord is providing that button in-app

verbal monolith
slate swan
#

At last downloaded pyhton

sick birch
slate swan
sick birch
primal token
#

it's probably for premium subscriptions

unkempt canyonBOT
#

discord.utils.format_dt(dt, /, style=None)```
A helper function to format a [`datetime.datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime "(in Python v3.10)") for presentation within Discord.

This allows for a locale-independent way of presenting data using Discord specific Markdown...
sick birch
#

Yeah but what does it actually do

primal token
#

Give more features igpithink

sick birch
#

Hmm

#

I wonder if they'll accept me if I say something like I'm staff on python discord so I know a lot about discord bots?

Saddest sentence ever

primal token
#

Does anyone know the commission percentage?

primal token
sick birch
#

Probably

primal token
sick birch
#

I've been out of the discord bots for a while

#

Just gets tedious after a while

primal token
slate swan
#

Discord most likely doesn't care at all about that but yeah you never know

austere gust
#

yo

#
intents = discord.Intents.default()
intents.members = True
bot = commands.Bot(command_prefix='.', intents=intents)```
#

my commands stopped working, prob something is messed up w my intents

#

do you guys have any ideas?

slate swan
#

I see no commands in that code

#

Nor any information about what command may not work

#

Nor what exactly doesn't work

austere gust
#

bruh this isnt the whole code

slate swan
#

If you use prefix commands, enable the message_content intent

#

Consider moving to slash commands

austere gust
#

intents.message_content = True

slate swan
#

Yes

#

Also in developer portal

sick birch
#

We really ought to get a "doesn't working" tag

slate swan
#

And as said, consider moving to slash commands

austere gust
slate swan
austere gust
slate swan
austere gust
sick birch
#

"My code doesn't work"
Ok - so did your computer blow up? That would make your code not work, yes?

slate swan
#

Google is your friend

#
python -m pip install -U discord.py
onyx cipher
#

how do I use discord.Role.members

austere gust
#

ty

slate swan
#

You get a role object

#

And then use .members on it

sick birch
unkempt canyonBOT
sick birch
#

Returns a list[discord.Member]

onyx cipher
#

so member in property members: ?

#

how would I define it as a variable

#

so members = property members ?

slate swan
#
m = role.members
#

m will be a list of members

onyx cipher
#

ok tq tq

slate swan
#

Before you come back, role is a role object

#

That must be defined

onyx cipher
#

yeh

austere gust
#

now my bot starts, but still cant use the commands

sick birch
#

Did you enable both in code AND the dev portal?

austere gust
#

yepp

#
intents = discord.Intents.default()
intents.members = True
intents.message_content = True```
austere gust
sick birch
#

Are the intents actually being passed into the constructor?

austere gust
#

uh?

sick birch
#

Can I see the bot constructor?

austere gust
#

u want the code?

sick birch
#

Erm initializer I think the term is

#

Too much Java 🥴

austere gust
#

intializer??

sick birch
#

the bot = commands.Bot(...) stuff

austere gust
#

bot = commands.Bot(command_prefix='.', intents=intents)

sick birch
#

hmmm

#

You're sure you saved the file? All changes took effect? The token is of the same application whose message content intents you had enabled?

austere gust
#

bruhhh am not dumb

#

and events work, commands not

#

on_message events work

sick birch
# austere gust bruhhh am not dumb

I'm not insulting your intelligence, sorry if it came out that way. It's just a lot more common than you think. Number #1 rule of troubleshooting is "check if the PC is on" for a reason 😛

austere gust
#

I use bot.run to start my bot, I guess it is not a problem, or is it outdated?

sick birch
#

Is your on message an event or a listener?

austere gust
#

listener

#

they works

#

commands not..

sick birch
#

Can I see the code for it?

#

Just to be sure

austere gust
#

but why u need on_messsage if they works lol

sick birch
#

Just humour me

austere gust
sick birch
#

Thought it'd be something like that

austere gust
#

yeh ty

austere gust
# sick birch Yup
@bot.listen()
async def on_message(message):
    if message.content.startswith('asd'):
        await message.channel.send("asd")``` Now I changed, but now this on_message listener doesn't work 😂
sick birch
#

Doesn't work how? Is the event being triggered?

austere gust
#

yeah I write asd

#

and nothing happens

sick birch
#

That's inside the if though

slate swan
#

I believe you need something like

if member.status == discord.Status.offline:
    # Stuff

or

if member.status == "offline":
    # Stuff
austere gust
maiden fable
#

does the second one also work? Nice

slate swan
#

I think so at least

#

Would make sense it does

maiden fable
#

You might wanna check for str(member.status) btw

#

Because iirc that surely works

slate swan
#

Yeah I'd use the first one ideally

maiden fable
#

Well doesn't seem to work

slate swan
#

Intents?

maiden fable
#

Ik I ain't got the presence intent, but I was just checking the comparing method

#

Since without intent, my status is returned as offline

slate swan
#

And if you str() it

maiden fable
#

offline

#

Well the eval command by default str()'s it

slate swan
#

Yeah

maiden fable
#

is the Editor class from PIL or smth?

slate swan
#

Not related to the code you've sent

maiden fable
#

Don't load it everytime then
Your CPU usage will 📈

slate swan
#

You've never defined background, or in another scope

maiden fable
#

Load it once on startup

maiden fable
#

Use a botvar or smth

#

!botvar

unkempt canyonBOT
#

Python allows you to set custom attributes to most objects, like your bot! By storing things as attributes of the bot object, you can access them anywhere you access your bot. In the discord.py library, these custom attributes are commonly known as "bot variables" and can be a lifesaver if your bot is divided into many different files. An example on how to use custom attributes on your bot is shown below:

bot = commands.Bot(command_prefix="!")
# Set an attribute on our bot
bot.test = "I am accessible everywhere!"

@bot.command()
async def get(ctx: commands.Context):
    """A command to get the current value of `test`."""
    # Send what the test attribute is currently set to
    await ctx.send(ctx.bot.test)

@bot.command()
async def setval(ctx: commands.Context, *, new_text: str):
    """A command to set a new value of `test`."""
    # Here we change the attribute to what was specified in new_text
    bot.test = new_text

This all applies to cogs as well! You can set attributes to self as you wish.

Be sure not to overwrite attributes discord.py uses, like cogs or users. Name your attributes carefully!

slate swan
#

Required intents missing in example Run

#

hi

maiden fable
slate swan
#

so i have a generator bot for discord made in python

#

and if i type .gen giftcard (Example) in general it should sent something like You can not generate in this channel, go to #generator

#

and if i go in #generator it should work
someone knows how to do it

#

Against ToS, against rules - won't get help

slate swan
#

Intents missing

#

Presence intent

#

bro im not good at python

#

why

#

man it was example

#

Either way it is not allowed.

#

i dont want to generate nitro...

#

Nitro generators are, quite obvious, not allowed

#

man it was examplee

#

Your message clearly stated nitro generators

#

i dont want to generate nitro..

#

bruh

#

Unsure if you will get access to it for that usage

#

You can always try, but they may tell you to remove the status icon from the message

#

I'd go ahead and see what they respond

#

Yeah you can test on that one

#

yoikes

feral frost
#

how can i get server id without ctx ?

#
def add_kick(member: discord.Member):
    if os.path.isfile(f"servers/kick{id}.json"):
        with open(f"servers/kick{id}.json", "r") as fp:
            data = json.load(fp)
        try:
            data[f"{member}"]["kicked"] = True
        except KeyError:
            data[f"{member}"] = {"kicked": True}
    else:
        data = {f"{member}": {"kicked": True}}

    with open(f"servers/kick{id}.json", 'w+') as fp:
        json.dump(data, fp, sort_keys=True, indent=4)``` it for in here
slate swan
#

What do you have at disposition

feral frost
#

id has to be the id

slate swan
#

Well, pretty sure you can use member.guild.id

feral frost
#

nope didnt work i already tried that one

slate swan
#

Or simply pass the guild ID as new parameter

#

might be a dumb question but how can I send multiple embeds with await interaction.channel.send()?

feral frost
slate swan
#

You can pass a new parameter which would be the guild ID

feral frost
#

? do i have to manually put 100 guild ids in ther ?

slate swan
#

????

feral frost
#

but it worked before i just forgot what it was

slate swan
#
def add_kick(m: discord.Member, guildID: int):
    # Stuff

# In your command:
add_kick(ctx.member, ctx.guild.id)
feral frost
#

but i want the json file to be called like the id

slate swan
#

So?

#

You call the function with the guild ID as parameter

#

You can use it anywhere in your function

feral frost
#

and how i make a json file from it

slate swan
#

The same way as you do now???

feral frost
feral frost
slate swan
#

You have id for the server ID

feral frost
#

that doesnt say that

slate swan
#

Then use guildID in your function to reference the guild ID

feral frost
#

ok lets try it

slate swan
#

Then create your files or whatever you want with that parameter in your function and replace {id} with {guildID} or whatever the parameter you want

feral frost
#

k it works

slate swan
#

Probably want to also go for memberID instead of member

feral frost
#

hmm

#

why ?

slate swan
#

IDs are unique and can't change

feral frost
#

ill put the discriminator behind it

slate swan
#

Member names and discriminators can change

feral frost
#

ok

#

ill do that

halcyon basalt
#
import discord

class MyClient(discord.Client):
    async def on_ready(self):
        print('Logged on as', self.user)

    async def on_message(self, message):
        # don't respond to ourselves
        if message.author == self.user:
            return

        if message.content == ('Complete your payment'):

            await message.channel.send('checkout detected ![beastrocket](https://cdn.discordapp.com/emojis/1020342626827894895.webp?size=128 "beastrocket") \n@halcyon basalt')
        if message.content == ('Complete Order'):
            await message.channel.send('checkout detected ![beastrocket](https://cdn.discordapp.com/emojis/1020342626827894895.webp?size=128 "beastrocket") \n@halcyon basalt')
        if message.content == ('PayPal Link'):
            await message.channel.send('checkout detected ![beastrocket](https://cdn.discordapp.com/emojis/1020342626827894895.webp?size=128 "beastrocket") \n@halcyon basalt')
        if message.content == ('Successful Checkout'):
            await message.channel.send('checkout detected ![beastrocket](https://cdn.discordapp.com/emojis/1020342626827894895.webp?size=128 "beastrocket") \n@halcyon basalt')
        if message.content == ('Complete your Order'):
            await message.channel.send('checkout detected ![beastrocket](https://cdn.discordapp.com/emojis/1020342626827894895.webp?size=128 "beastrocket") \n@halcyon basalt')
                        
 

intents = discord.Intents.default()
intents.message_content = True
client = MyClient(intents=intents)
```i want to read embed to found this keyword but i don't know how 
when i start my bot and i send enbed the bot not respond
#

thx in advance

#

pls help me

slate swan
#

You're reading message content and not embed content

#
message.embeds[index]

will return the embed object

#

Then you can search in the embed description, title, etc. By using message.embeds[index]. description for example

#

index would be 0 if there is just a single embed sent

#

So

if message.embeds[0].description == "Complete your payment":
    # Your stuff

Note that it will only be true if it matches exactly the text.

You may want to use

if "Complete your payment" in message.embeds[0].description:
    # Stuff here

if you want to check if the description contains the text and eventually more/other text

#

Hopefully that helps bunNod2

soft compass
#
import discord
import random
client = discord.Client(intents=discord.Intents.message_content())
@client.event 
async def on_ready():
    
  lst = ["Hello", "Hi","yo"]
  general_channel = client.get_channel(1003479064872497244)
  random_num = random.randint(0,2)
  await general_channel.send((lst[random_num]))
@client.event
async def on_message(message):
        if message.content == '!test':
         await message.channel.send("Testing")
client.run('Token')

why won't it receive input?

slate swan
#

Your bot will never send the Testing message for two reasons
• You are checking if the author of the message is the bot, if not it will do nothing
• You are missing the message_content intent

soft compass
#

ohh

#

lemme try that

#
import discord
import random
client = discord.Client(intents=discord.Intents.message_content())
@client.event 
async def on_ready():
    
  lst = ["Hello", "Hi","yo"]
  general_channel = client.get_channel(1003479064872497244)
  random_num = random.randint(0,2)
  await general_channel.send((lst[random_num]))
@client.event
async def on_message(message):
        if message.content == '!test':
         await message.channel.send("Testing")
client.run('Token')

it says flag_value object is not callable line 3

slate swan
#

!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. By default discord.py has all intents enabled except for Members, Message Content, and Presences. These are needed for features such as on_member events, to get access to message content, and to get members' statuses.

To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.

Next, in your bot 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

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

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

For more info about using intents, see the discord.py docs on intents, and for general information about them, see the Discord developer documentation on intents.

slate swan
#

Replace intents.members with intents.message_content for your case

soft compass
#

Do i have to import the stuff on top

#

like discord.ext, commands and intents

slate swan
#

Not necessarily, you can use

import discord

intents = discord.Intents.default()
...
soft compass
#

ok thanks

#
intents = discord.Intents.message_content()
client = discord.Client(intents)

like this?

slate swan
#

No, look the example again

slate swan
#
intents = discord.Intents.default() # Don't change
intents.members = True # Change for message_content

client = discord.Client(intents=intents)
soft compass
#

lemme see

slate swan
# slate swan .
if ctx.channel.id != YOUR_CHANNEL_ID:
    # Your code if in wrong channel
    return

# Your code if in correct channel

ctx may be message if you're using it in an event (@bot.event that is most likely on_message) and not a command (@bot.command())

soft compass
#
import discord
import random
intents = discord.Intents.default()
intents.message_content = True
client = discord.Client(intents=intents)
@client.event 
async def on_ready():
  lst = ["Hello", "Hi","yo"]
  general_channel = client.get_channel(1003479064872497244)
  random_num = random.randint(0,2)
  await general_channel.send((lst[random_num]))
@client.event
async def on_message(message):
        if message.content == '!test':
         await message.channel.send("Testing")
client.run('Token')

still whenever i test the command it doesent work and the problem still persists

slate swan
#

Seems like you have some indentation problems here

#

!indents

unkempt canyonBOT
#

Indentation

Indentation is leading whitespace (spaces and tabs) at the beginning of a line of code. In the case of Python, they are used to determine the grouping of statements.

Spaces should be preferred over tabs. To be clear, this is in reference to the character itself, not the keys on a keyboard. Your editor/IDE should be configured to insert spaces when the TAB key is pressed. The amount of spaces should be a multiple of 4, except optionally in the case of continuation lines.

Example

def foo():
    bar = 'baz'  # indented one level
    if bar == 'baz':
        print('ham')  # indented two levels
    return bar  # indented one level

The first line is not indented. The next two lines are indented to be inside of the function definition. They will only run when the function is called. The fourth line is indented to be inside the if statement, and will only run if the if statement evaluates to True. The fifth and last line is like the 2nd and 3rd and will always run when the function is called. It effectively closes the if statement above as no more lines can be inside the if statement below that line.

Indentation is used after:
1. Compound statements (eg. if, while, for, try, with, def, class, and their counterparts)
2. Continuation lines

More Info
1. Indentation style guide
2. Tabs or Spaces?
3. Official docs on indentation

slate swan
#

Make sure to respect these correctly

verbal monolith
#
if message.author.id in USER_IDS:
        response = [f'shut up, {username}', 'be quiet.', 'shush.']
        await message.channel.send(random.choice(response))
    elif message.author.id == 951975771730235465:
        response = [f'shut up, {username}']
        await message.channel.send(random.choice(response))```
how would i change this to a dictionary?
slate swan
#

Wording in your snippets are, again, pretty weird/offensive

But essentially a dictionary is

x = {
    "key": "value"
}

So can't help you nore as you don't specify what needs to be the key and what the value. But you might figure that out by yourself

slate swan
#

shut up, {username}
is targeted to someone, so kind of offensive

verbal monolith
slate swan
#

Then no need to use them if you don't necessarily need them - otherwise we'd need more information on why you want to use dictionaries and for what exactly

#

Because saying

how would i change this to a dictionary?

Isn't helpful at finding what you want to achieve

whole kite
#
@client.command(name="quadratic_equation", help="this is the Quadratic Equation")
async def quadratic_equation(ctx, a: int, b: int, c:int):
    discriminant = (b**2) - (4*a*c)
    solution1 = (-b+cmath.sqrt(discriminant)) / (2*a)
    solution2 = (-b-cmath.sqrt(discriminant)) / (2*a)
    embed = discord.Embed(title="Answer :",description=solution1, "\n" + solution2)
    embed.set_footer(text="Made by Hamza.#0065")
    await ctx.send(embed=embed)```
#

im tryna have two variables in teh discord embed

slate swan
#

!f-strings

unkempt canyonBOT
#

Creating a Python string with your variables using the + operator can be difficult to write and read. F-strings (format-strings) make it easy to insert values into a string. If you put an f in front of the first quote, you can then put Python expressions between curly braces in the string.

>>> snake = "pythons"
>>> number = 21
>>> f"There are {number * 2} {snake} on the plane."
"There are 42 pythons on the plane."

Note that even when you include an expression that isn't a string, like number * 2, Python will convert it to a string for you.

whole kite
slate swan
#

No need to send, read the embed.

#

Use f-strings instead

soft compass
#

It still wont receive input

import discord
import random
intents = discord.Intents.default()
intents.message_content = True
client = discord.Client(intents=intents)
@client.event 
async def on_ready():
  lst = ["Hello", "Hi","yo"]
  general_channel = client.get_channel(1003479064872497244)
  random_num = random.randint(0,2)
  await general_channel.send((lst[random_num]))
@client.event
async def on_message(message):
        if message.content == '!test':
         await message.channel.send("Testing")
client.run('Token')
whole kite
#

F'?

slate swan
slate swan
soft compass
soft compass
slate swan
#

You sometimes have like 2 spaces and sometimes 4 or a tab and then use 2 spaces in-between

#

Be consistent

verbal monolith
slate swan
#

Yeah that too, probably want to run some prettier on the code

#

Or just add some new lines after the imports and between the events etc. manually

verbal monolith
#

i.e look at my code

soft compass
#

i put it through a formatter it changed it quite alot but its still not receiving input whenever I say the command

verbal monolith
#

hwat command

soft compass
#

!test

whole kite
#

thanks krypton

sick birch
#

You can just do

username, user_message, channel = message.author.name, message.content, message.channel.name

or

username = message.author.name
user_message = message.content
channel = message.channel.name
primal token
#

Being explicit would be better in terms of readability

sick birch
#

i prefer the latter yeah

dull terrace
#

does this mean someone is ddosing my ec2 instance with aws

pale iris
#

your code
!e

    if len(tuples) == 1 and next(iter(tuples))[i] != 0: return (next(iter(tuples)),)
    usefulHere = {t for t in tuples if t[i] != 0}
    if not usefulHere: return False
    for t in usefulHere:
        attempt = search(tuples - {t}, i + 1)
        if attempt:
            return (t,) + attempt
    return False
A = ((1, 0, 0), (0, 0, 1), (1, 1, 0))
res = search(set(A))
print(res)

A = ((1, 0, 0, 1), (0, 0, 1, 0), (1, 1, 0, 0), (0, 0, 0, 1))
res = search(set(A))
print(res)```py
slate swan
#

You need the ```py I think

pale iris
#

Like that?

#

Cause I’m using already ```

unkempt sinew
#

how to remove people from discord teams

rugged shadow
#

maybe you have a terribly unoptimized command, but there is a chance someone is ddosing you

crimson anvil
#

hello could someone help please with this program? i'm having issue with this right now and don't know if there are other problems 'int' object has no attribute 'shuffle'
import random

current = 0
random = 0
Fel = 0

List_lif = [
["Hur gammal är du?", "21"],
["Vilken årstid är vi på nu?", "Höst"],
["vad är korta namnet för central processor unit?", "cpu"],
["vad står GPU för?", "graphics processor unit"],
["vad står RAM för?", "random access memory"],
["vad är Microsofts operativsystem?", "windows"],
["vem är CEO:n av Microsoft?", "satya nadella"],
["Hur många MB är en GB?", "1024"],
["Till vilket företag tillhör core i9 processorer", "intel"],
["Tänker du köpa RTX 4090?", "ja"],

]

while True:
current.shuffle(List_lif)
answer1 = input(list_lif[0][0])
if answer1 == list_lif[0][1]:
print("Rätt")
score += 1

elif answer1 != List_lif:
print("Fel svar")
score += 0
Fel = 1

i = input("Vill du förtsätta?" "\na)Ja \nb) Nej")
if i == "Ja":
continue
print(answer1)

elif i == "Nej":
print("Bra jobbat")
print("Du fick" + str(score) + "Rätt")
print("Du fick" + str(Fel) + "Fel")
score = float(score / 10) * 100
print(score, "%")
if score >= 60:
print("Godkänd")
else:
print("Underkänd")
exit()

print("Du fick") + str(score + "Rätt")
print(score, "%")
if score >= 60:
print("Godkänd")
else:
print("Underkänd")

fading marlin
#

use codeblocks, and how is this related to discord bot development?

obtuse blaze
#

So im hosting my bot atm on heroku (I have free paid subscription) and im using SQLite3 / aiosqlite and everytime I deploy a new update all the information stored on db is lost since Heroku doesn't save it. Is there any way to fix this?

obtuse blaze
#

so it makes this around

#

block around code

obtuse blaze
#

well what else could I use

#

that its either free or cheap and would fix this problem?

fading marlin
obtuse blaze
#

humm I cant see that channel XD

fading marlin
#

it's a thread on this channel

obtuse blaze
#

discord-bots-meta?

#

oh ty

primal token
dull terrace
light jungle
#

Hello, I have a question, can I somehow implement a check of how many people are sitting with the microphone / headphones turned off in the voice channel. And if, for a certain time, his headphones and microphone are turned off, give out a temporary role and shoot after it is blurred?

sick birch
#

!d discord.on_voice_state_update see here for more info on how to do that

unkempt canyonBOT
#

discord.on_voice_state_update(member, before, after)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member") changes their [`VoiceState`](https://discordpy.readthedocs.io/en/latest/api.html#discord.VoiceState "discord.VoiceState").

The following, but not limited to, examples illustrate when this event is called...
mighty pilot
#

Is it a good idea to open and close a database connection at the beginning and end of a command instead of just being connected when the program starts? I'm going to make something that uses a temporary table in Mariadb which means I'm gonna have to rewrite my commands such that I open and close the connection when the command is issued instead of just being connected when the bot starts

slate swan
#

use aiomysql for the purpose

drifting cypress
#

Hello , is there any way to get the last message of a channel ?(using discord's APi)

slate swan
#

GET request to /channels/{channel.id}/messages then you have the list of messages, you can easily find the last message sent aka index 0

slate swan
#

If you use an API wrapper like discord.py you can use

#

!d discord.abc.Messageable.history

unkempt canyonBOT
#

async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)```
Returns an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator "(in Python v3.10)") 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...
slate swan
#

There is an example shown on how to get the messages, and the last sent will also be at index 0

drifting cypress
lone shard
#

Boy

#

Bot*

woeful quartz
#

!google translate

#

fuck

torn sail
#

Is it better to have a bot with lots of features or a bot focused on 1 feature?

slate swan
#

Depends what that one feature is. You can focus on one concept though and have multiple features and commands around that.

#

The era of multipurpose should finally move away, if that's what you want to do

keen dust
#

Hey guys, I deployed a discord bot with repl.it and uptime robot but I'm only able to get a maximum uptime of 1 hour, I've configured everything but after I close my tabs the bot lasts for 1 hour maximum and its out

#

after it shuts down it gives me an https error but it works after I run it half an hour later

austere gust
#

Hey, on message event doesnt have a reply attribute?

#

Also can I ignore letter case somehow?

zealous jay
#

Convert to lowercase

keen dust
#

use .lower() or .upper()

zealous jay
#

^

keen dust
#

I miss hosting my bot on vsc even though it utilized my resources 😢

zealous jay
#

You can apply for the github student dev pack

slate swan
#

don't host on vsc

zealous jay
#

If you are a student

keen dust
#

ik

#

I'm using repl'it now

#

but the uptime robot feature doesn't seem to work

slate swan
#

thats worse

keen dust
#

it works maximum for an hour with tabs closed

keen dust
austere gust
slate swan
#

just use ur terminal to run the bot

austere gust
#

where do I put it?

#

becuase if I say 'Van admin tgf' then it won't answer 'Nincs'

slate swan
#

the string you want to lower

#

i.e. the message.content

austere gust
#
@bot.listen("on_message")
async def on_message(message):
    if .lower("van admin tgf?") in message.content:
        await message.channel.send("Nincs!")```
slate swan
#

hey can sb help me

#

i try to code a bot

slate swan
#

and there is a mistake in it

austere gust
#
@bot.listen("on_message")
async def on_message(message):
    if message.content.lower("van admin tgf?") in message.content:
        await message.channel.send("Nincs!")```
#

Like this?

keen dust
#

and you need ctx

slate swan
#

can sb help me?

austere gust
#

eh but at on_message I cant use ctx

#

or can I?

cloud dawn
zealous jay
#

no, you need to lower the message that was sent

keen dust
#

oop sorry I thought it was another function didn't notice on_message lol

unkempt canyonBOT
cloud dawn
austere gust
#

ty

zealous jay
#

i think the bot.proccess i thing is not necessary as its a listener

austere gust
zealous jay
#

It's not overwriting the event

cloud dawn
slate swan
#

is it possible to run other asyncio function in the same file as discord bot/client?

slate swan
#

how

#

@cloud dawn

cloud dawn
#

How?

#

It's possible but I have no clue with that you want to do.

#

Run 2 commands at the same time then you run 2 async functions at the same time.

#

What is in the "discord bot/client" file.

austere gust
#

ty @cloud dawn

obtuse blaze
ocean bough
#

Hi there , I'm just had tried create a discord bot according to freecodecamp youtube video.But have an issue that the bot only respond via dm channel and not respond normal channel. Any idea?

slate swan
ocean bough
#

should I implement to code or via developer portal application settings ?

#

my code is currently like that: discord.Client(intents=discord.Intents.default())

dull terrace
obtuse blaze
#

oh truee

#

I forgot that

dull terrace
cloud dawn
dull terrace
cloud dawn
#

Oh then it just got undocumented.

#

Haven't made a bot in awhile so dunno.

ocean bough
hushed galleon
#

bot.loop was never documented but they havent changed it either

#

asyncio.create_task(...) would also be sufficient since you're usually creating that task from the same event loop anyway

slate swan
#

does anyoen know this

#

what i did wrong 2022-10-20 17:54:53 ERROR discord.client Ignoring exception in on_ready
Traceback (most recent call last):
File R\AppData\Roaming\Python\Python310\site-packages\discord\client.py", line 409, in _run_event
await coro(*args, **kwargs)
File \Discord bot.py", line 9, in on_ready
test_channel = await client.get_channel(1032312979594682491)
TypeError: object TextChannel can't be used in 'await' expression

slate swan
silent portal
#

so test_channel = client.get_channel(1032312979594682491)

slate swan
#

still saying error

silent portal
#

which new error

slate swan
#

see

#

2022-10-20 17:56:51 ERROR discord.client Ignoring exception in on_ready
Traceback (most recent call last):
File \AppData\Roaming\Python\Python310\site-packages\discord\client.py", line 409, in _run_event
await coro(*args, **kwargs)
File "\Discord bot.py", line 11, in on_ready
test_channel = send('Hello')
NameError: name 'send' is not defined

silent portal
#

I think u mixed some things up

slate swan
#

import discord
import http

client = discord.Client(intents=discord.Intents.all())

@client.event
async def on_ready():

test_channel = client.get_channel(1032312979594682491)

test_channel = send('Hello')

client.run('')

#

there

dull terrace
#

test_channel.send

silent portal
#
import discord
import http

client = discord.Client(intents=discord.Intents.all())

@client.event
async def on_ready():

  test_channel = client.get_channel(1032312979594682491) 

  await test_channel.send('Hello')

client.run('')```
slate swan
slate swan
#

ok

#

YAYYYYYYYYYY OMFG TYSM

slate swan
silent portal
#

uhm yeah sure but that's some basic stuff xd

#

but yw :)

slate swan
#

and watching youtube

#

and i did everything right but it was still wrong

silent portal
#

the '=' sign is to declare a variable, not executing a function

slate swan
#

@silent portal

#

help me pls

#

myEmbed = discord.Embed(title="Current version", description="The bot is in version 1.0"=0x00ff00)
^
IndentationError: unindent does not match any outer indentation level what did i do wrong

dull terrace
#

if i'm checking if something is an emoji through len(), emojis can't be longer than 2 right?

silent portal
dull terrace
#

i want something simple to figure out if a string is a single emoji

slate swan
silent portal
dull terrace
#

everything else is 9+ characters

hushed galleon
#

i guess a length check would be as simple as it gets

dull terrace
#

and yeah you can measure len for emojis

dull terrace
#

oop

silent portal
dull terrace
#

!e

print(len("🤦🏼‍♂️"))
unkempt canyonBOT
#

@dull terrace :white_check_mark: Your 3.11 eval job has completed with return code 0.

5
dull terrace
silent portal
slate swan
slate swan
dull terrace
silent portal
slate swan
#

import discord
import http

client = discord.Client(intents=discord.Intents.all())

@client.event
async def on_ready():

test_channel = client.get_channel(1032312979594682491)

await test_channel.send('Hello')

@client.event
async def on_message(message):

if message.content == 'what is the version':
    test_channel = client.get_channel(1032312979594682491) 
   
   myEmbed = discord.Embed(title="Current version", description="The bot is in version 1.0", color=0x00ff00)

await ctx.send(embed=myEmbed)
myEmbed.add_field(name="Version Code:", value="v1.0.0", inline=True)
myEmbed.add_field(name="Date Released:", value="October 20th, 2022", inline=False)
myEmbed.set-footer(text="This is a sample footer")
myEmbed.set_author(name="One Piece")

    await test_channel.send('The version is 1.0!')

client.run('')

silent portal
slate swan
#

see that

silent portal
#

u gotta change some things up

slate swan
silent portal
#

lemme help

slate swan
#

ok i need to go in some min

hushed galleon
#

@dull terrace personally ive used the emoji package to check if its an emoji, they have a bunch of constants defined

silent portal
#
@client.command()
async def version(ctx):
    embed = discord.Embed(title="Current version", description="The bot is in version 1.0", color=0x00ff00)
    await ctx.send(embed=embed)
#

@slate swan ^^

slate swan
#

yes

silent portal
#

try this and remove the other things u have there

slate swan
#

question, let's say I have a command that iterates through a list with over 100k entries or I want ti do large iterations. Wont comprehensions and for loops create small blocks as I can't run multiple loops concurrently?

sick panther
unkempt canyonBOT
#

Indentation

Indentation is leading whitespace (spaces and tabs) at the beginning of a line of code. In the case of Python, they are used to determine the grouping of statements.

Spaces should be preferred over tabs. To be clear, this is in reference to the character itself, not the keys on a keyboard. Your editor/IDE should be configured to insert spaces when the TAB key is pressed. The amount of spaces should be a multiple of 4, except optionally in the case of continuation lines.

Example

def foo():
    bar = 'baz'  # indented one level
    if bar == 'baz':
        print('ham')  # indented two levels
    return bar  # indented one level

The first line is not indented. The next two lines are indented to be inside of the function definition. They will only run when the function is called. The fourth line is indented to be inside the if statement, and will only run if the if statement evaluates to True. The fifth and last line is like the 2nd and 3rd and will always run when the function is called. It effectively closes the if statement above as no more lines can be inside the if statement below that line.

Indentation is used after:
1. Compound statements (eg. if, while, for, try, with, def, class, and their counterparts)
2. Continuation lines

More Info
1. Indentation style guide
2. Tabs or Spaces?
3. Official docs on indentation

dull terrace
#
async def gui(user, partner, event=None, item=None):
    end, buttons = f"{user.scavanging_run}#{user.id}#{partner.id}", []
    for label, custom in config.EVENT_GUI[event]:
        if len(label) < 8:
            buttons.append(Button(emoji=label, custom_id=f"{custom}{end}"))
        else:
            if partner.nick > 15:
                partner.nick = partner.nick[:12] + "..."
            label = label.replace("partner", partner.nick[:15])
            label = label.replace("loot", item)
            buttons.append(Button(label=label, custom_id=f"{custom}{end}"))
    return [ActionRow(*buttons)]

this is the code so far, should make it a lot easier to just pull labels and the start of custom ids from a dictionary

slate swan
sick panther
#

first of all you should change to commands.Bot in order to use commands properly actually, also it looks like you don't really got basic python knowledge. consider learning it first, it will help you a lot

slate swan
#

but if i make an bot with soem code i can learn from it

silent portal
#

watch some youtube videos, the basics are easy to learn

slate swan
#

this is the last time

sick panther
#

getting into discord bot development really won't do that much

slate swan
#

i really need help i have training and need to go

sick panther
slate swan
#

but i want this to work

slate swan
#

man i am stressing

sick panther
#

your indentation is off, you will need to fix it in order to use your stuff. i wont give you a whole lesson about it now, but after every : in python, you will need to indent the next code block, unless you dont want to do anything after those statements

slate swan
#

indentation is common python knowledge brah

sick panther
#

^

slate swan
#

bruh yk what i dont understand a bit sorry

#

its like when you write an essay and you have to indent, somewhere in your code that indentation isn't proper

#

but i need to go i rlley wanted it to work before i left oh well i will try tmr or today night bue guys ty fo rthe help

primal token
#

"common" isnt the best word to use, base/basic knowledge would be more appropriate

hushed galleon
#

@dull terrace btw according to this emoji package the longest emoji is 10 characters long

sick panther
slate swan
#

typehints

dull terrace
#

7739monkathink seeing as i'm putting in the emojis ill just have to check i don't use a huge one

#

i think those are the weird combo emojis

primal token
unkempt canyonBOT
#

@primal token :warning: Your 3.11 eval job has completed with return code 0.

[No output]
fair hinge
#

Well you're just storing it

primal token
primal token
fair hinge
#

It doesn't really matter if you indent or not(unless required). It entirely depends on what you wish.

sick panther
hushed galleon
sick panther
hushed galleon
#

dang you actually wrote em >.>

primal token
#

Yeah sorry, but your statement isnt fully correct

hushed galleon
#

discord's builtin emoji selector cant handle it

sick panther
#

emoji*

fair hinge
primal token
#

Your point makes no sense with my context

#

thats like asking about an apple and getting a document about a banana

sick panther
#

wasnt the context that they did need to learn basics (indentation mainly)

fair hinge
#

Isn't indentation included in the basics of almost all programming languages?

primal token
#

no?

#

some languages arent based on indentation

sick panther
#

ok its not a programming language sorry

sick panther
#

i think brainfuck doesnt have intendatiom

primal token
#

i wouldnt say almost all of them either but sure

sick panther
#

just out of interest, which one would be in your head rn

fair hinge
#

So, what's your point?

primal token
#

Either way, my point is in python indentation doesnt depend on colon placement

sick panther
#

oh

primal token
#

Do you expect something else?

fair hinge
#

¯_(ツ)_/¯

sick panther
primal token
#

But your context was too generally and i corrected it

sick panther
#

nothing more nothing less, lools like we misunderstood each other

#

will be more specific next time, ty

primal token
#

👍

slate swan
#

You probably have a string somewhere and a float and try to put them together, the library you're using doesn't like that

#

!e

val = '10'
x = 1.2
z = val*x
unkempt canyonBOT
#

@slate swan :x: Your 3.11 eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 3, in <module>
003 | TypeError: can't multiply sequence by non-int of type 'float'
slate swan
#

Check that your values are actual integers or floats depending on what you need

#

Your percentage is a string, needs to be an integer

#

I suppose result_level[4] is your percentage

#

If that's the case just give that in percentage=...

#

You are passing a string

#

You need to pass the integer

#
percentage="..." # Not good

percentage=20 # Good
#

So now find what the percentage is

#

And provide that only

#

Well that will never work

#

You need to provide one single integer

#

You can't just remove the "" and think it will work

#

Since I don't know what result_level[4] and result_level[3] is, can't really help

#

Again, no.

#

Provide one single integer

#

Stop trying with result_level[4] and result_level[3]

#

If result_level[3] is the XP needed for the next level and result_level[4] the current level, then do the simple maths behind percentage

#

It's just the maths behind percentage

#

result_level[3] is 100%
result_level[4] is X%

#

Rule of three

#

Nothing related to python, that's one of the first rules you learn at school in maths class

silent portal
slate swan
#

I mean, I can send the way to calculate that but I believe you've learned that at school so not needed

silent portal
#

coding is like math too

#

like the logic kinda

slate swan
#

Search for the rule of three on google

#

There's probably a picture with a table and the easy calculation behind it

silent portal
#

dreisatz ;)

slate swan
#

yeah

slate swan
#

and find the operators

#

eh no

#

!e

current = 26
next_level = 873

percentage = 100*current/next_level
print(percentage)
unkempt canyonBOT
#

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

2.9782359679266897
slate swan
#

Never looked at that in maths?

slate swan
#

You probably did

#

Otherwise really look a youtube video about that, it's one of the only thing in maths that I still use these days

#

Well that's the table

#

wait

#

the 100 stays

#
| %   | XP         |
|-----|------------|
| 100 | next_level |
| X   | current    |
#

You have all 3 just not X

#

So X = current * 100 / next_level

#

Multiply both in diagonals and divide by the remaining one, next_level

#

int(...) as it may return a float

#

Should be fine

silent portal
#

@slate swan can u send me a fr rq

slate swan
#

Oh, convert these to ints

#

Like every value

#

int(int(result_level[3])....)

north escarp
#
class event(commands.Cog):
    def __init__(self, bot):
        self.bot = bot




    @commands.Cog.listener()
    async def on_member_join(member):
        channel1 = self.bot.get_channel(767370104814960640)
        await channel1.send(f"{member} has joined the server")

    @commands.Cog.listener()
    async def on_member_join(member):
        channel2 = self.bot.get_channel(766620766237753345)
        await channel2.send(f"{member} has left the server")```
why does he swear at me on self and say that there is an error, although everything is ok in other files ??
slate swan
#
                          |
                          V
async def on_member_join(self, member):

                          |
                          V
async def on_member_join(self, member):
north escarp
#

just highlights with an orange wavy line

slate swan
#

Note that you have twice the same event, might want to rename the other one

north escarp
slate swan
#

Why you using {} in the middle

#

It's a function, use ()

#

And you are missing an int() around result level 4

slate swan
#

Send me that line

#

I'll clean it up you're using way too many ()

#

What type does the function threshold return

drifting cypress
#

i just tried to get a channel's message with get , and can't get it to work 😭
here's my code:

slate swan
#

so it returns an int

drifting cypress
#

import requests
import json
def retrieve_messages(channelid):
headers={
'authorization': '' "

}
r=requests.get(f'https://discord.com/api/v9/channels/{channelid}')
jsonn=json.loads(r.text)
print(jsonn)
for value in jsonn:
    print(value, '\n')

retrieve_messages('1032709297383145492')
author hidden on purpose

slate swan
#

Also use code blocks

#

!codeblock

unkempt canyonBOT
#

Here's how to format Python code on Discord:

```py
print('Hello world!')
```

These are backticks, not quotes. Check this out if you can't find the backtick key.

drifting cypress
slate swan
#

Then you're not authorized to get the messages list

#

In that channel

#
int(100*int(result_level[4])/threshold(result_level[3]))

Should be fine

drifting cypress
#

weird , cause i got the authozisation , how am i suppose to fix this ?

slate swan
#

What authorization did you give?

#

Bot token?

drifting cypress
slate swan
#

So a user token

#

That's self botting and is not allowed as per Discord's ToS

drifting cypress
#

ah fk , so how can i get a bot token ?

slate swan
#

Create a new application, then switch to the "Bot" panel and create a bot

#

You will then see that

#

Which you can then get a token from

drifting cypress
#

oki , thx ❤️

slate swan
#

Then the header will be

Authorization: Bot TOKEN_HERE
drifting cypress
# slate swan You will then see that

when i click on add bot it says "Too many users have this username, please try another." :/ i've already created a new account but still displaying this

north escarp
#

And in order to make a message with buttons, you just need the message id and the standard creation of buttons, as for commands ?

slate swan
#

Too many bots with the same name so they don't allow it

slate swan
drifting cypress
north escarp
slate swan
#

You can do it anywhere

#

Event, command, etc.

north escarp
#

Can I add a button to existing messages ?

slate swan
#

If it was sent by the bot, yes - edit the message and add a view

#

question, let's say I have a command that iterates through a list with over 100k entries or I want ti do large iterations. Wont comprehensions and for loops create small blocks as I can't run multiple loops concurrently?

drifting cypress
#

annnd i got an other error

import requests
import json
def retrieve_messages(channelid):
    he={
    'authorization': Bot 'hidden'

    }
    r=requests.get(f'https://discord.com/api/v9/channels/1032709297383145492/messages' ,headers=he)
    jsonn=json.loads(r.text)
    print(jsonn)
    for value in jsonn:
        print(value, '\n')

retrieve_messages('1032709297383145492')

it says invalid sintax , and if i remove the "bot" part it says Unauthorized

slate swan
#

Everything needs to be in quotes

#
headers = {
  "Authorization": "Bot TOKEN"
}
drifting cypress
slate swan
#

Means the bot doesn't have the permission

#

Needs the VIEW_CHANNEL and READ_MESSAGE_HISTORY permission for the bot

drifting cypress
slate swan
#

Oh that should go in the invite

drifting cypress
#

in the invite ? i need to add an invite part ?

slate swan
#

Meaning when inviting the bot to the server, you need to add that number in the URL such as

https://discord.com/oauth2/authorize?client_id=<client_id>&scope=bot+applications.commands&permissions=<permissions_number>
#

Then go on that page and invite the bot in the server where the channel is

drifting cypress
#

oh , the bot wasn't on the server.... XD

slate swan
#

yep

drifting cypress
#

do i have to log in as the bot or can i do it directly on the app menu ?

slate swan
#

You click go the URL that's it

#

Then choose the server where the channel is

#

And it'll be added

drifting cypress
silent portal
#

looks cute tho

#

nice work

slate swan
#

guys

#

whats the new discord like install

silent portal
honest shoal
#

it's now released on PyPi, so can be done directly (pip install discord.py)

silent portal
#

oh didn't know that

slate swan
#

I'd recommend using

python -m pip install discord.py
#

In case you have multiple Python installations

#

You are sure it will be installed for the installation that is used for the python command

#

@slate swan

#

it shows him error w client but we dont have client in the code

#

Don't know why you're opening that in the embedded Python

#

Use python file.py to execute your file

slate swan
#

Then use python main.py

#

In your terminal or cmd

#

worked

#

finally

drifting cypress
#

thought i was done with it... but the dictionnary obtained with the json shows than the message contain nothing but it does... "content" is empty

slate swan
#

Oh yeah enable the message content intent in the developer portal in bot tab

#

same place where you got the token

#

if you scroll you see a privileged intent section, look for the "Message Content" one and enable that

#

should be good after that

drifting cypress
slate swan
drifting cypress
#

so even with admin it can't read messages ? weird

slate swan
#

Click on your app, then "Bot" section

#

Then scroll down and toggle the check under "Message Content"

slate swan
slate swan
drifting cypress
# slate swan Then scroll down and toggle the check under "Message Content"

i enabled it and even with it being enabled it's still displaying nothing :/

 {'id': 'hidden', 'username': 'impérial x', 'avatar': '0d9a2658ddf9441824b512d932618e9f', 'avatar_decoration': None, 'discriminator': '7800', 'public_flags': 64}, 'attachments': [], 'embeds': [], 'mentions': [], 'mention_roles': [], 'pinned': False, 'mention_everyone': False, 'tts': False, 'timestamp': '2022-10-20T17:38:23.474000+00:00', 'edited_timestamp': None, 'flags': 0, 'components': [], 'message_reference': {'channel_id': '735188487615283232', 'guild_id': '729837326120910915'}}
slate swan
#

Once the check is enabled should be fine

slate swan
#

Try sending a new message and checking again

drifting cypress
slate swan
#

@silent portal

#

you wanna help me?

#

Go on, just say

#

ok soo

#

i am doing an bot and i did this why is my bot not responding when i say "what day is it?" it should say the day is 21th but it doesnt

#

from cgi import test
from math import degrees
import discord
import http

client = discord.Client(intents=discord.Intents.all())

@client.event
async def on_ready():

test_channel = client.get_channel(1032312979594682491)
await test_channel.send('Hello')

@client.event
async def on_disconnect():
test_channel = client.get_channel(1032312979594682491)
await test_channel.send('Hello')

@client.event
async def on_message(message):

if message.content == "What day is it?":
    test_channel = client.get_channel(1032312979594682491)
    await test_channel.send("The day is the 21th")

@client.event
async def on_message(message):

if message.content == "Thank you for telling me!":
    test_channel = client.get_channel(1032312979594682491)
    await test_channel.send("No Problem AnyTime :)")

client.run('')

#

!codeblock

unkempt canyonBOT
#

Here's how to format Python code on Discord:

```py
print('Hello world!')
```

These are backticks, not quotes. Check this out if you can't find the backtick key.

slate swan
#

Yes

#

and why the bot is not respondig the first time but the second time

#

Though next time use code blocks so that it's easier to read

slate swan
#

how do i do that

slate swan
#

so i just say !codeblock

#

!codeblock this