#discord-bots

1 messages · Page 785 of 1

lunar quail
maiden fable
#

Bruh

delicate thorn
#

for purge command when i do ;clear 5 it says cleared 5 messages but the message "cleared 5 messages" its not being deleted

cold sonnet
#

since you send a message, there's one message more that you have to delete

#

or it's just the way you sent it

#

did you send it after the purge?

maiden fable
#

@lunar quail people just change browser key that's it

#

Ig discord patched the way?

slate swan
lunar quail
neat pagoda
#

My Bot IsVerified, How do I make it where I can see constant cpu usage?

if mes =='&botinfo':
      users= await get_bank_data()
      bedem = discord.Embed(title = 'System Resource Usage', description = 'See CPU and memory usage of the system.',color=discord.Color.orange())
      bedem.add_field(name = 'CPU Usage', value = f'{psutil.cpu_percent()}%', inline = False)
      bedem.add_field(name = 'Memory Usage', value = f'{psutil.virtual_memory().percent}%', inline = False)
      bedem.add_field(name = 'Available Memory', value = f'{psutil.virtual_memory().available * 100 / psutil.virtual_memory().total}%', inline = False)
      server=len(client.guilds)
      bedem.add_field(name='Total Users',value=len(users))
      bedem.add_field(name='Total Servers',value=server)
      bedem.add_field(name='version',value='2.0')
      bedem.add_field(name='Verification Status',value='Verified!!')
      await ctx.channel.send(embed=bedem)
velvet tinsel
#

oh god

slate swan
velvet tinsel
#

okimii help me

lunar quail
velvet tinsel
#

please

#

okimii save me

slate swan
#

wait wait wait

velvet tinsel
slate swan
#

why are you using aiosqlite but json?

final iron
cold sonnet
#
import discord
from discord.ext import commands
import random
from random import choice
from itertools import cycle
import os
import json
import random
import datetime
import requests
import aiosqlite
import asyncio
from typing import Text
from discord.ext import tasks
from discord.ext.commands import clean_content
import aiohttp
import platform
from aiohttp import ClientSession
import time
neat pagoda
neat pagoda
#

I was thinking tasks.loop but that didn't work

lunar quail
slate swan
#

requests and aiohhtp?

#

yes

#

just why

cold sonnet
#

a little bit of everything, all of the time

lunar quail
#

lemme read what you were doing, hold on

velvet tinsel
#
import time
intents = discord.Intents.all()
bot = commands.Bot(command_prefix="+",intents=intents)
bot.version = "1.0"
bot.remove_command('help')
@bot.command(name="ping")
async def ping(ctx: commands.Context):
    await ctx.send(f"**Pong! {round(bot.latency * 1000)}ms**")
@bot.command(name="invite")
async def invite(ctx: commands.Context):
    await ctx.send(" **Witaj jeżeli chcesz mnie dodać na swój serwer tutaj masz link ...**")
@bot.command(name="Support")
async def Support(ctx: commands.Context):
    await ctx.send(" **Jeżeli chcesz dowiedzieć się informacji dotyczących bota uzyskać pomoc czy popisać z ludzmi to masz tutaj link do serwera support ...

my eyes

slate swan
#

why import aiosqlite if youre gonna use json as a db

cold sonnet
#

lacking unnecessary code breaks to be able to say you did it only in 30 lines

slate swan
#

exactly

velvet tinsel
#

i'm concerned mainly about the lack of spaces and the bot.command(name=...)

lunar quail
#

If there is a roasting vacancy then it's time for my code to get roasted then Sansky

velvet tinsel
#

and also aiosqlite but json db

lunar quail
#

it is not that great, I am fixing some stuff

cold sonnet
#
    @commands.command()
    async def help(self, ctx):
        return```
slate swan
lunar quail
#

and will delete later

lunar quail
slate swan
#

you have a good repo with a trash main

slate swan
lunar quail
slate swan
lunar quail
#

in tys

cold sonnet
#

nah

slate swan
cold sonnet
#

make commands in on_message

slate swan
cold sonnet
#

in just the main file

velvet tinsel
lunar quail
velvet tinsel
#

why commands in on_message

lunar quail
velvet tinsel
#

just wonderingg

velvet tinsel
cold sonnet
#

default on_message process commands -> override it and process commands yourself

lunar quail
#

ah okay

slate swan
cold sonnet
#

spared time

cold sonnet
#

P R A C T I C A L I T Y

velvet tinsel
#

W H A T

lunar quail
#

On a scale of 1 to 10 how well do y'all rate the code quality of that repo? smugW

slate swan
#

update_presence task in on_ready?

class rename_(commands.Cog):``` 
rip pep8
cold sonnet
#
    @commands.command()
    async def help(self, ctx):
        return``` out of ten
lunar quail
#

wasn't gonna hardcode it anyway

velvet tinsel
#

I haven't checked a lot tho

cold sonnet
slate swan
#

not bad but needs work

#

<:

velvet tinsel
slate swan
#

nope overall

lunar quail
slate swan
#

nice <:

slate swan
lunar quail
#

@bot.event
async def on_ready():
    print(f"Successfully logged in as {bot.user}")
    bot.usage_cache = await get_usage_of(bot.db, "global")
    if not update_presence.is_running():
        update_presence.start()

Only listener for on_ready

slate swan
#

and the task does not have a wait_until_ready

#

just use the kwarg

lunar quail
slate swan
#

im ignoring globals you used...

slate swan
velvet tinsel
slate swan
#

global variables, but its fine there ig?

#

your rating is now 3

cold sonnet
#

lmao

lunar quail
velvet tinsel
lunar quail
#

which is far worse by design

slate swan
#

good work imo

lunar quail
#

I wish y'all read the comment which mention the used of globals

lunar quail
#
    global _prev, _count
    """
    We are interested in having overall command usage as the bot's rpc
    And this value being reflected in the rpc instantaneously after command usage is satisfactory
    If there are multiple changes in minimal duration of time then the rpc should not spam requests to the discord api
    here we will enforce our own limit to prevent such an occurence. This limit (in seconds) is dictated by MIN_DELAY_OF_RPC
    Albeit the database can handle multiple requests in a second (in terms of resources)
    We will not be checking the db every seconds because it is bad from a design perspective
    Instead we will be caching this under bot.prev_cache and inheritents of commands.Cog will manipulate this value
    Such way requests to the database can be kept to an minimum and be performant
    """
cold sonnet
#

where do you host that bot

#

Achxy

lunar quail
cold sonnet
#

what's that

slate swan
lunar quail
slate swan
slate swan
lunar quail
# lunar quail thanks mate

@velvet tinsel @slate swan all latter solutions are severely slower or much more resource consuming.
wrong self reply smh

slate swan
#

im gonna check some codes in github

slate swan
#

can you really not delete unicode from a string?

#

when im waitin on replay on my problem from staff from danbothost

lunar quail
#

better yet and I dont have to remove it but use a appropriate parser

slate swan
#

no unicode escapes

#

\uD83C

#

example

#

like raw

#

not dpy related?

lunar quail
#

which did what you just said now

slate swan
#

ic

lunar quail
#

It is a feature I dropped later

slate swan
#

i cant manage to parse it i keep getting decoding errors

lunar quail
unkempt canyonBOT
#

class discord.ext.commands.Greedy```
A special converter that greedily consumes arguments until it can’t. As a consequence of this behaviour, most input errors are silently discarded, since it is used as an indicator of when to stop parsing.

When a parser error is met the greedy converter stops converting, undoes the internal string parsing routine, and continues parsing regularly.

For example, in the following code:

```py
@commands.command()
async def test(ctx, numbers: Greedy[int], reason: str):
    await ctx.send("numbers: {}, reason: {}".format(numbers, reason))
```  An invocation of `[p]test 1 2 3 4 5 6 hello` would pass `numbers` with `[1, 2, 3, 4, 5, 6]` and `reason` with `hello`...
lunar quail
#

FINALLY

slate swan
#

wth what i find on my github profile xd but is not releted to discord

cold sonnet
#

but database....

velvet tinsel
slate swan
#

you dont , you can just store their id , and get/fetch it whenever you need the object

slate swan
lunar quail
velvet tinsel
lunar quail
#

Now I just use Optional or Union and call it a day

slate swan
velvet tinsel
lunar quail
#

it works and typehints must be a good practice :p

slate swan
#

where i can chat on a topic not related to python? sorry for asking here but idk where i can ask

unkempt canyonBOT
slate swan
#

~

#

nvm

velvet tinsel
#

nvm

slate swan
#

imagine using classes for making commands.

lunar quail
slate swan
velvet tinsel
lunar quail
#

preferences ig

slate swan
#

no

#

better handling

#

nah i dont mean the Bot object

#
import lightbulb
from lightbulb.ext import filament

class EchoCommand(filament.CommandLike):
    implements = [lightbulb.SlashCommand, lightbulb.PrefixCommand]

    name = "echo"
    description = "repeats the given text"

    text_option = filament.opt("text", "text to repeat")

    async def callback(self, ctx):
        await ctx.respond(ctx.options.text)
``` this is funny
lunar quail
#

I think someone rating my project 6 and a 9 is pretty nice UY99_codm_kek

velvet tinsel
slate swan
#

out of?

lunar quail
#

oh cuz of globals

slate swan
lunar quail
lunar quail
cold sonnet
slate swan
#

im to slow

lunar quail
#

check the code

slate swan
#

well i'd say if you change the class names to PascalCase and use bot variables instead of globals , it would be better

cold sonnet
#

y

lunar quail
# cold sonnet y

it has the botvar, it is actively checking if the previous var is same as new before making an api call

slate swan
#

but again, you have a reason to not use botvar

lunar quail
slate swan
#

yea agreed , and you dont name the global variable something which you would use often

lunar quail
#

At that point, having an class for Cache would be a much better idea

lunar quail
slate swan
lunar quail
slate swan
#

what are you gonna cache

lunar quail
#

probably will do it soon tho, it indeed doesn't look professional

lunar quail
#

this is to make significantly less fetch requests from the database

#

and provide a faster solution

#

and made me resort to use gloabals

slate swan
#
ModuleNotFoundError: No module named 'discordheximals'

🚶

#

the eternal error

slate swan
#

i was gonna use it for my hikari project

#

💀

slate swan
final iron
#

Whats the point of discordheximals anyway

#

Just use discord hex

slate swan
#

no

lunar quail
#

and we came to my solution of gloabls

slate swan
# slate swan

just do

from discordheximals import discordheximals
lunar quail
#

beautiful full circle UY97_codm_kek

final iron
final iron
#

Good

slate swan
#

no joke

final iron
#

Can I help?

#

I have no clue what I'm doing

#

Never contributed to a project ever

slate swan
#

i have a task for you :))

slate swan
final iron
slate swan
quaint epoch
#

so, my bot joins a vc, i want i play song.mp3 that has the rickroll, but it says that it is not voice connected, (ideally when it joins it's supposed to have a green ring around it signaling that it is voice connected) but it doesn't do that by default, how can i do that when i join the vc?

final iron
velvet tinsel
slate swan
final iron
#

So I know what to do

slate swan
slate swan
#

hello i want to make a command that sends command via webhook

#

!d discord.Webhook.send

unkempt canyonBOT
#

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

Sends a message using the webhook.

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

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

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

its hard to explain

#

basically i command like !hello and it responds hello in webhook form

lunar quail
#

comment there (or here) if have any suggestions and I'll do them

final iron
#
def get_default_prefix(file="config.json", key="DEFAULT_PREFIX"):
#

JSON

#

aaaaaaa

echo wasp
#

Hello can you help me i made this code on a bot without cogs and now i put it into cog form but it can't define a bunch of stuff is that a visual studio error or what do i need to fix to make this work? https://paste.pythondiscord.com/ejixulefom.py

river flare
#

how can i get the user tha created/deleted a channel?

final iron
lunar quail
#

this is json file is to prevent circular imports and better plug and play

echo wasp
#

even if i fix it

final iron
#

Whats undefined

final iron
echo wasp
echo wasp
#

all of that

echo wasp
#

@final iron

#

why are you putting your github link with a message that doesn't need it?

dire folio
#

how can i get the link of a message?

lunar quail
dire folio
#

ty

river flare
#

i have thos command but i get this error ```python
sql = "INSERT INTO customers (name, code) VALUES (%s,%s)"
val = (user,test)
mycursor.execute(sql, val)
mydb.commit()

in redeem
mycursor.execute(sql, val)
Command raised an exception: MySQLInterfaceError: Python type Member cannot be converted

lunar quail
river flare
lunar quail
slate swan
#

you cant store a member obj

#

store his id

lunar quail
#

ctx.author is a Member object, it has the name attribute

slate swan
#

use his id

#

not name

lunar quail
#

You can either store it as name (customer, it can be changed) or id as the guy above mentioned which constant throughout the span of discord account

slate swan
#

id is better

#

its a snowflake

lunar quail
# slate swan id is better

it is, but since the column name is customer it is safer to assume the database is containing the lexical names and not the ids

#

which is why I gave the help for name

slate swan
#

what if hes storing accounts and the user changes his name?

lunar quail
slate swan
#

still why use name?

lunar quail
slate swan
#

just save the customer by id or store it with both and just check the id

lunar quail
slate swan
#

yes

velvet tinsel
#

evening okimii and Achxy

compact ruin
#

Guys how do i add these buttons?

late wigeon
#

I'm trying to setup a bot to use slash commands in a cog using the pycord library. how do I do this cause nothing I try is working

slate swan
unkempt canyonBOT
#

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

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

New in version 2.0.
slate swan
velvet tinsel
compact ruin
final iron
compact ruin
final iron
slate swan
compact ruin
#

O-

compact ruin
#

well link but yh

slate swan
#
raise discord.ClientException(f'Callback for {self.name} command is missing "self" parameter.')
discord.errors.ClientException: Callback for elemental command is missing "self" parameter.
    @commands.command(aliases=['game', 'elementel', 'element', 'ele'], pass_context=True)
    @commands.guild_only()
    async def elemental():
        embed = discord.Embed(title="Elemental - A horror masterpiece",
        description="\"elemental\" some info.\n"
                    "info and stuff.\n"
                    "ahysgsa.", color=invisible_color)
        embed.set_thumbnail(url="https://cdn.discordapp.com/attachments/934929464620613742/934954348214108160/Logo_Black.jpg")
        embed.set_footer(text=footertext, icon_url=footerimg)

Any idea on why i'm getting this ? i never saw this

slate swan
#

yea i'm dumb

compact ruin
slate swan
#

but ill recommend a fork

#

like disnake

compact ruin
#

but dont work

#

do i delete the one i already have or...?

pliant gulch
#

Can you go into your code and print discord.__version__?

compact ruin
#

@slate swan

slate swan
slate swan
pliant gulch
# slate swan hey andy whats a context manager? confused on the topic
with open("file") as fp:
    ...
``` For an example, in the above code we run `open` via context manager which handles opening the file, placing the file pointer into `fp` then later **closing** the file after we exist the context manager. If we only did `fp = open("file")` it would open but not close it later
compact ruin
#

oof its not 2.0

pliant gulch
#

You aren't on v2.0

pliant gulch
compact ruin
#

Got it

#

andd now it messed up my cogs-

compact ruin
#

cause i see a _ui but no .ui

slate swan
#

.ui

compact ruin
#

.ui apparently does not exist

dire folio
#

how do i do a hyperlink in an embed?

slate swan
compact ruin
#

from discord.ui right

slate swan
compact ruin
#

i did

from discord.ui
#

but it wont work

slate swan
#

why

#

no need to import it its inside disnake

compact ruin
#

o-

slate swan
compact ruin
#

Uhh it just threw my cogs out the window-

dire folio
slate swan
#

yw

slate swan
river flare
#

hello. I have this command, but i get as an output the text file, while i want to get the number of its lines. e.x. 3. ```python
with open('test.txt') as f:
lines = f.readlines()
emb=nextcord.Embed(title="Ainta test", description=f"", color=color, timestamp=datetime.now())
emb.add_field(name="RockStars", value=f'{lines}')
await channel.send(embed=emb)

wicked atlas
river flare
polar ice
#

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

kindred epoch
#
def check(m):
    return m.author.id == message.author.id and m.message.id == message.id

any idea why this is raising this error?

kindred epoch
#

so im supposed to have before and after in place of m?

wicked atlas
#

yep, each one being the message object before and after the edit

kindred epoch
#

alright thanks

quaint epoch
#

when my bot connects to vc, how do i make it connect to voice?

#

bc it doesn't connect to voice for me

slim ibex
#

A bot can’t talk?

#

in a vc

#

Unless it’s doing music I guess

quaint epoch
slim ibex
#

mhmm

quaint epoch
#

it worked for me before when i played song.mp3 with the rickroll, but it doesn't

#

now*

slim ibex
#

!d discord.VoiceChannel

unkempt canyonBOT
#

class discord.VoiceChannel```
Represents a Discord guild voice channel.

x == y Checks if two channels are equal.

x != y Checks if two channels are not equal.

hash(x) Returns the channel’s hash.

str(x) Returns the channel’s name.
slim ibex
#

ah ok

#

Well I have never worked with voice channels and discord bots so this is beyond me

quaint epoch
#

an hour ago, when bot joined a vc it had a green circle around it and it played teh .mp3, now it don't

slate swan
#

how do i install disnake

river flare
#

Hey. i have this but i want to delete acc after usage.

    user = ctx.author
    with open('accounts.txt', "r+") as f:
        lines = f.readlines()
    acc = "".join(random.choice(lines) for i in range(1))
    channel = ctx.message.channel
    hwid_stmt = "SELECT COUNT(*) FROM customers WHERE name = %s"
    cursor = mydb.cursor()
    cursor.execute(hwid_stmt, (user.name,))
    hwid_count = cursor.fetchone()[0]
    if hwid_count == 0:
        emb=nextcord.Embed(title="Invalid license", description=f"You are not a customer!", color=0x9f1414, timestamp=datetime.now())
        await channel.send(embed=emb)
    else:

        emb=nextcord.Embed(title="Ainta Gen", description=f"{acc}", color=color, timestamp=datetime.now())
        await channel.send(embed=emb)
slate swan
river flare
#

pip install disnake i think

slate swan
#

okokokok

#

not workign brother

river flare
slate swan
#

no really

#

ok im sorry

wicked atlas
# slate swan

Here it shows that it's being installed on Python 3.10, but in your last screenshot it shows you are running it with Python 3.9

#

Two different interpreters

slate swan
#

alr how do i install python 3.10

wicked atlas
slate swan
#

OH

#

their on 3.9

#

ok so i need to install 3.9

#

rip

wicked atlas
#

No, you don't need to install anything

#

You just need to run your code with the 3.10 installation instead of the 3.9

#

Or, install disnake on the 3.9

slate swan
#

wtf

#

explain

slate swan
#

await ctx.delete()

#

i think or await ctx.message.delete()

#

and dont forget to mention it on top

#

so like (ctx, message)

echo wasp
compact ruin
#

Does anyone know how to check if a reaction has been removed (discord py) i cant find it in api or im just blind

quaint epoch
#

!d disnake.VoiceClient

wicked atlas
unkempt canyonBOT
#

discord.on_reaction_remove(reaction, user)```
Called when a message has a reaction removed from it. Similar to on\_message\_edit, if the message is not found in the internal message cache, then this event will not be called.

Note

To get the message being reacted, access it via [`Reaction.message`](https://discordpy.readthedocs.io/en/master/api.html#discord.Reaction.message "discord.Reaction.message").

This requires both [`Intents.reactions`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.reactions "discord.Intents.reactions") and [`Intents.members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.members "discord.Intents.members") to be enabled.

Note

Consider using [`on_raw_reaction_remove()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_raw_reaction_remove "discord.on_raw_reaction_remove") if you need this and do not want to enable the members intent.
quaint epoch
#

hmmm

compact ruin
quaint epoch
#

!d disnake.VoiceClient

unkempt canyonBOT
#

class disnake.VoiceClient```
Represents a Discord voice connection.

You do not create these, you typically get them from e.g. [`VoiceChannel.connect()`](https://docs.disnake.dev/en/latest/api.html#disnake.VoiceChannel.connect "disnake.VoiceChannel.connect").

Warning

In order to use PCM based AudioSources, you must have the opus library installed on your system and loaded through [`opus.load_opus()`](https://docs.disnake.dev/en/latest/api.html#disnake.opus.load_opus "disnake.opus.load_opus"). Otherwise, your AudioSources must be opus encoded (e.g. using [`FFmpegOpusAudio`](https://docs.disnake.dev/en/latest/api.html#disnake.FFmpegOpusAudio "disnake.FFmpegOpusAudio")) or the library will not be able to transmit audio.
river flare
#
left = 5

@j1mk0l.command()
async def gen(ctx):
    user = ctx.author
    left -= 1
```it doesnt recognise it. How can i fix that?
river flare
#

left

final iron
#

What do you mean?

#

Undefined error?

velvet tinsel
#

maybe global or use it as a local variable

river flare
velvet tinsel
#

pithink it can't be accessed through the function

river flare
#

so what should i do?

velvet tinsel
#

what are you trying to do?

river flare
#

everytome i use the command, it removes 1 from left

velvet tinsel
#

solution depends, I'm trying to delay using global as much as possible

velvet tinsel
unkempt canyonBOT
#

7.12. The global statement


global_stmt ::=  "global" identifier ("," identifier)*
``` The [`global`](https://docs.python.org/3/reference/simple_stmts.html#global) statement is a declaration which holds for the entire current code block. It means that the listed identifiers are to be interpreted as globals. It would be impossible to assign to a global variable without `global`, although free variables may refer to globals without being declared global.

Names listed in a [`global`](https://docs.python.org/3/reference/simple_stmts.html#global) statement must not be used in the same code block textually preceding that `global` statement.

Names listed in a [`global`](https://docs.python.org/3/reference/simple_stmts.html#global) statement must not be defined as formal parameters, or as targets in [`with`](https://docs.python.org/3/reference/compound_stmts.html#with) statements or [`except`](https://docs.python.org/3/reference/compound_stmts.html#except) clauses, or in a [`for`](https://docs.python.org/3/reference/compound_stmts.html#for) target list, [`class`](https://docs.python.org/3/reference/compound_stmts.html#class) definition, function definition, [`import`](https://docs.python.org/3/reference/simple_stmts.html#import) statement, or variable annotation.
final iron
#

I've never needed to use global

velvet tinsel
quaint epoch
#

!d disnake.Guild.voice_client

unkempt canyonBOT
#

property voice_client: Optional[VoiceProtocol]```
Returns the [`VoiceProtocol`](https://docs.disnake.dev/en/latest/api.html#disnake.VoiceProtocol "disnake.VoiceProtocol") associated with this guild, if any.
velvet tinsel
#

?

river flare
velvet tinsel
river flare
#

i still get "left" is not defiened

velvet tinsel
#

let's see the code

river flare
#
def test():
  global left
  left = 5

test()

@j1mk0l.command()
async def gen(ctx):
    user = ctx.author
    left -= 1
velvet tinsel
#

well...you didn't define left

#

you have to define it first

#

before accessing it from the function

#

and if you want left with gen() you'd also need to 🤮 global t

final iron
#

!global

unkempt canyonBOT
#

When adding functions or classes to a program, it can be tempting to reference inaccessible variables by declaring them as global. Doing this can result in code that is harder to read, debug and test. Instead of using globals, pass variables or objects as parameters and receive return values.

Instead of writing

def update_score():
    global score, roll
    score = score + roll
update_score()

do this instead

def update_score(score, roll):
    return score + roll
score = update_score(score, roll)

For in-depth explanations on why global variables are bad news in a variety of situations, see this Stack Overflow answer.

velvet tinsel
#

!d global ?? what

unkempt canyonBOT
#

7.12. The global statement


global_stmt ::=  "global" identifier ("," identifier)*
``` The [`global`](https://docs.python.org/3/reference/simple_stmts.html#global) statement is a declaration which holds for the entire current code block. It means that the listed identifiers are to be interpreted as globals. It would be impossible to assign to a global variable without `global`, although free variables may refer to globals without being declared global.

Names listed in a [`global`](https://docs.python.org/3/reference/simple_stmts.html#global) statement must not be used in the same code block textually preceding that `global` statement.

Names listed in a [`global`](https://docs.python.org/3/reference/simple_stmts.html#global) statement must not be defined as formal parameters, or as targets in [`with`](https://docs.python.org/3/reference/compound_stmts.html#with) statements or [`except`](https://docs.python.org/3/reference/compound_stmts.html#except) clauses, or in a [`for`](https://docs.python.org/3/reference/compound_stmts.html#for) target list, [`class`](https://docs.python.org/3/reference/compound_stmts.html#class) definition, function definition, [`import`](https://docs.python.org/3/reference/simple_stmts.html#import) statement, or variable annotation.
final iron
#

What

velvet tinsel
#

I...is that a command?

#

!global

#

shit

final iron
#

Yes, why?

final iron
velvet tinsel
#

oh

#

I thought it was supposed to be !d

#

nvm

final iron
#

Well d is an aliases for docs which is short form for documentation

velvet tinsel
#

yeah ik

final iron
#

So I sent the tag on global where as you sent the documentation

velvet tinsel
#

o

final iron
#

I don't really think you should be advertising globals to people unless the solution is unnecessarily complex

velvet tinsel
#

I tried to delay it as long as possible

boreal ravine
river flare
#

no matter what i use, i still cant fix "left" is not defiened

river flare
velvet tinsel
visual island
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!

final iron
velvet tinsel
visual island
#

yeah

velvet tinsel
visual island
#

:CH_ThumbsUpSmile:

#

oh

#

my nitro ends?

#

no alright

velvet tinsel
#

lmao

final iron
#

I'm so bored

#

Give me ideas on things to make

#

Please

boreal ravine
final iron
#

Seems you already solved it

velvet tinsel
#

wait no

#

nvm I forgot it

#

make your own API for discord @final iron

boreal ravine
#

discord already has an api

velvet tinsel
#

shit

#

I meant API wrapper

#

wtf am I talking about

boreal ravine
#

there are tons of api wrappers for discord out there, what makes yours unique from others if you make one

velvet tinsel
#

he's bored

#

what else can people do

green bluff
#

im trying to learn image manipulation but i got this error

final iron
green bluff
#

any help

velvet tinsel
velvet tinsel
green bluff
#

yes

velvet tinsel
#

ok

#

can you show me your file structure?

final iron
velvet tinsel
#

idk

#

no ideas

green bluff
#
@client.command()
async def test(ctx, reason):
    mc = Image.open("miencraft.jpeg")
    title_font = ImageFont.truetype('playfair/playfair-font.ttf', 200)
    asset = ctx.author.avatar_url_as(size = 128)
    data = BytesIO(await asset.read())
    pfp = Image.open(data)
    image_editable = ImageDraw.Draw(mc)
    title_text = f'{reason}'
    pfp = pfp.resize((93,93))

    mc.paste(pfp, (103,34))
    mc.paste(image_editable.text((103,34), title_text, (237, 230, 211), font=title_font))
    mc.save("profile.jpeg")
    

    await ctx.send(file = discord.File("profile.jpeg"))```
#

is this file structure?

green bluff
#

oh okay

velvet tinsel
#

wtf am I talking about

alsothat's your code

#

file structure is like

my folder 
-- some_file.txt
--something_else.txt
green bluff
#

so is it the path to my folder or all the files in my folder

#

C:\Users\notvi\OneDrive\Desktop\Mjc project

velvet tinsel
#

no

#

I meant file structure sorry

boreal ravine
green bluff
velvet tinsel
#

I need to deal with sleep paralysis demons

green bluff
#

its jsut the text is not working

velvet tinsel
#

nice to know

tardy plume
#

how to inline embed field?

velvet tinsel
#

!d discord.Embed

unkempt canyonBOT
#

class discord.Embed(*, colour=Embed.Empty, color=Embed.Empty, title=Embed.Empty, type='rich', url=Embed.Empty, description=Embed.Empty, timestamp=None)```
Represents a Discord embed.

len(x) Returns the total size of the embed. Useful for checking if it’s within the 6000 character limit.

bool(b) Returns whether the embed has any data set.

New in version 2.0.

Certain properties return an `EmbedProxy`, a type that acts similar to a regular [`dict`](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.9)") except using dotted access, e.g. `embed.author.icon_url`. If the attribute is invalid or empty, then a special sentinel value is returned, [`Embed.Empty`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed.Empty "discord.Embed.Empty").

For ease of use, all parameters that expect a [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)") are implicitly casted to [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)") for you.
velvet tinsel
#

there should be an inline kwarg

#

like inline=True or something

tardy plume
#

i have this

embed.add_field(name=f'EST+0 {est.strftime(format)}', value=esttz, inline=True)
#

but this is the result

velvet tinsel
#

well you wanted them to inline

#

what do you want them to look like

tardy plume
#

wait

velvet tinsel
#

waiting

tardy plume
#

inline is that and not inline is?

#

im kinda dumb xd

boreal ravine
green bluff
velvet tinsel
green bluff
velvet tinsel
quaint epoch
#

is there an event when the bot leaves a vc?

tardy plume
#

i want it to be column

velvet tinsel
#

c...column?

boreal ravine
tardy plume
#

like this

boreal ravine
#

you gotta do inline=False at the 4th field to do that, and so on

tardy plume
#

ok xd

boreal ravine
green bluff
#

I get a different error now

unkempt canyonBOT
#

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

The following, but not limited to, examples illustrate when this event is called...
boreal ravine
green bluff
#

suer

tardy plume
#

inline=False still looks like this

green bluff
tardy plume
#

kk

green bluff
#

an embed cant just expand out of ur screen

#

xD

green bluff
cedar stream
green bluff
#

and inline = True should be in the same line

cedar stream
#

Yes

boreal ravine
# green bluff

hm idrk you could check google for this iirc your error is related to the paste method

green bluff
#

oh kk

cedar stream
green bluff
#

im trying to add text to my image

cedar stream
#

With pillow?

green bluff
#

yes

#

so the tutorial im watching

#

is only for python

#

and im trying to kinda change the code a bit

#

to send it in discord

cedar stream
#

Lemme see

cedar stream
green bluff
#

how?

cedar stream
#

Try to remove .text

green bluff
cedar stream
#

Remove ()

#

And whatever is inside

green bluff
#

in the Image.draw() i remove () am i right

cedar stream
#

What happens if you try to draw text directly to mc inage

#

No

#

Where u just removed .text

#

U didnt remove (103…)

green bluff
#

remove this?

cedar stream
#

B4 you passed image_editable.text…

#

Now just pass image_editable

#

I wanna see what happens

green bluff
#

without the paramaters?

cedar stream
#

Just image_text

#

No

#

Sry my bad, It’ s image_editable

green bluff
#

i dont think i understand

cedar stream
#

It’ s not a function

green bluff
#

So what do i remove / add

#

do iremove the () in mc.paste?

cedar stream
#

The (103,14)

green bluff
#

oh

#

so i remove that

cedar stream
#

Try

green bluff
cedar stream
#

Yea nvm, I just checked how It’ s done

final iron
#

Are you using pil?

green bluff
#

yes i am

cedar stream
#

You do


from PIL import Image 
from PIL import ImageFont
from PIL import ImageDraw

font = ImageFont.truetype("times-ro.ttf", 24)

img = Image.new('RGB', (600, 400), color = 'red')

draw = ImageDraw.Draw(img)
draw.text((300, 200),"Hello World !",(0,0,0),font=font)

img.save('pil_red.png')

#

This is an example

#

You get a draw object and then do draw.text

green bluff
#

img = Image.new('RGB', (600, 400), color = 'red')

#

whats this line for

cedar stream
#

Just red background

#

Than you slap text on that red background

green bluff
#

oh ok

cedar stream
#

But that image could be anything

final iron
#

Maybe I should learn pillow for a welcome card?

#

Any reason pillow is preferred over opencv?

#

Because I know opencv

cedar stream
#

To turn the mf square into a circle

green bluff
#

this?

#

@cedar stream

cedar stream
#

Try it

#

I aint no interpreter

green bluff
cedar stream
#

Why do u paste x

#

Remove mc.paste(x)

green bluff
#

then how do i

cedar stream
#

draw.text adds text

green bluff
#

slap it on the backgroind

cedar stream
#

I’ m guessing

green bluff
#

oh k

#

tysm bro

surreal sierra
#

hey, I got this error not sure how to fix and have already tried a few things but it didnt solve the problem

 @commands.Cog.listener()  # this is a decorator for events/listeners
    async def on_guild_join(self, guild):
        with open('prefixes.json', 'r') as f:
            prefixes = json.load(f)

        prefixes[str(guild.id)] = '?'

        with open('prefixes.json', 'w') as f:
            json.dump(prefixes, f, indent=4)

        embed = discord.Embed(
            desscription=f"Hi everyone, I'm {self.bot} I hope you all are going to be pleased with my service, "
                         f"if you have any questions you can use the command `?help` or if you got something to "
                         f"report/suggest you can then tell my owner Physalia77 about it on github. \n `Current "
                         f"ping: {bot.latency * 1000} ms \n \n **OBS: THIS IS NOT A FINISH PROJECT, AND "
                         f"MANY THINGS CAN AND WILL BE CHANGED LIKE COMMANDS, BOT NAME, PROFILE PICTURE AND MORE",
            color=0x3498DB),

        await guild.text_channels[0].send(embed=embed)

OBS, problem is that the bot doesnt send the embed when it joins a new server

visual island
#

embed is a tuple, remove the last , comma

slate swan
#

!e print("hello\nworld")

unkempt canyonBOT
#

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

001 | hello
002 | world
worthy wadi
#

aids

surreal sierra
cedar stream
final iron
green bluff
cedar stream
frank tartan
#

how can i have my bot upload emojis?

cedar stream
#

!d discord.Emoji

unkempt canyonBOT
#

class discord.Emoji```
Represents a custom emoji.

Depending on the way this object was created, some of the attributes can have a value of `None`...
frank tartan
cedar stream
cedar stream
#

!d discord.Guild

unkempt canyonBOT
#

class discord.Guild```
Represents a Discord guild.

This is referred to as a “server” in the official Discord UI.

x == y Checks if two guilds are equal.

x != y Checks if two guilds are not equal.

hash(x) Returns the guild’s hash.

str(x) Returns the guild’s name.
slate swan
cedar stream
cedar stream
slate swan
#

lol

quaint epoch
surreal sierra
green bluff
#

my imasge quality is so low

#

any way to fix it or just get a different fgile

#

file

slate swan
#

is disnake

#

the best option

#

or should i get discord py 2.0,

#

pycord... blah blah blah

final iron
slate swan
#

ok but wiat

#

dont leave plspslps]

final iron
#

But I have never used pillow so idk

slate swan
#

not working

final iron
#

Why do you have discord.ActivityType[act]

slate swan
#

bc its for someone

#

Not sure if this is the right channel, it's been a while and I'm rusty. How do I get the bot to react to a specific users message. pls mention or reply thanks

#

and they dont know to much about programming and i want to make it simple

final iron
#

Well thats not how you're supposed to do it

boreal ravine
unkempt canyonBOT
#

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

Add a reaction to the message.

The emoji may be a unicode emoji or a custom guild [`Emoji`](https://discordpy.readthedocs.io/en/master/api.html#discord.Emoji "discord.Emoji").

You must have the [`read_message_history`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") permission to use this. If nobody else has reacted to the message using this emoji, the [`add_reactions`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.add_reactions "discord.Permissions.add_reactions") permission is required.
slate swan
#

alright bro

final iron
#

Its just

slate swan
#

how would u do it

#

@final iron

final iron
#

Don't randomly ping me

boreal ravine
unkempt canyonBOT
left crater
#
async def on_ready():
    print("Bot is ready!")
    await bot.change_presence(status=discord.Status.online,
                                 activity=discord.Game("%help"))``` @slate swan
#

u could do this

slate swan
#

uh no

final iron
slate swan
#

i want it like this

boreal ravine
slate swan
#

and also thats cursed

left crater
#

why

final iron
left crater
#

it works doesnt it

final iron
left crater
#

?

boreal ravine
boreal ravine
echo wasp
echo wasp
left crater
#

just make it play a game

final iron
boreal ravine
echo wasp
boreal ravine
#

yeah why use json

final iron
echo wasp
#

idc

boreal ravine
slate swan
#

What is earning defined as in your code

final iron
#

Check this out

echo wasp
slate swan
echo wasp
#

wait

slate swan
#

Basically means so that all your functions can access the variable

final iron
#

Should you really be recommending global variables?

#

Just define it in the method you want to use it in

echo wasp
slate swan
echo wasp
#

it hates the second one

#

and i do

#

in the 8 ems

final iron
slate swan
#

Yes so in this case wouldn't it be better to define it as a global variable

final iron
#

No

echo wasp
#

ok just please tell me how to fix it

final iron
#

You can always create a bot variable

#

!bot-var

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!

echo wasp
final iron
#

So?

echo wasp
#

so

#

so if i make the commands.command = bot will it fix it?

final iron
#

No?

#

I was suggesting you turn your random.randint() line in to a bot variable

echo wasp
#

show me example

slate swan
slate swan
#

Should be in your __init__ function

echo wasp
#

self.client

#

=client

#

is what i have defined

slate swan
#

Yes

#

global is real python

#

stop feeding people dpy garbage thats not teaching them anything

#

So what you'd do is ```py
self.client.test = "This is a string"

#

Jalyx is correct

echo wasp
#

so i need to add a self to it

slate swan
echo wasp
#

ok

slate swan
#

Yep pretty much

echo wasp
#

ugh didn't work

#

now it doesn't even run the bot

#

@slate swan

slate swan
#

Hm?

echo wasp
#

how do i define as like wut bot = random.int(10,100)

slate swan
#

Ok if you are going to use earnings multiple times, and the value is going to stay constant. I suggest defining the self.client.earnings = x variable in the __init__

echo wasp
#

oh

slate swan
#
self.client.earnings = random.randint(10,100)
#

I hope this is what you want

echo wasp
#

ok and then for the embed

#

how does it go in the embeds

#

same way?

#

because it tells me self is not defined

#

on what you told me

slate swan
#

what are you trying to do

echo wasp
#

when i define it

slate swan
#

so everything in your class can access the var

echo wasp
slate swan
slate swan
slate swan
#

its in the dunder

frank tartan
#
@client.command()
async def bold(ctx, text):
  ff.boldTEXT(text)
  await ctx.reply(text)

I have that in my main file and

def boldTEXT(text):
  text = text.replace("a", "𝗮")
  text = text.replace("b", "𝗯")
  text = text.replace("c", "𝗰")
  text = text.replace("d", "𝗱")
  text = text.replace("e", "𝗲")
  text = text.replace("f", "𝗳")
  text = text.replace("g", "𝗴")
  text = text.replace("h", "𝗵")
  text = text.replace("i", "𝗶")
  text = text.replace("j", "𝗷")
  text = text.replace("k", "𝗸")
  text = text.replace("l", "𝗹")
  text = text.replace("m", "𝗺")
  text = text.replace("n", "𝗻")
  text = text.replace("o", "𝗼")
  text = text.replace("p", "𝗽")
  text = text.replace("q", "𝗾")
  text = text.replace("r", "𝗿")
  text = text.replace("s", "𝘀")
  text = text.replace("t", "𝘁")
  text = text.replace("u", "𝘂")
  text = text.replace("v", "𝘃")
  text = text.replace("w", "𝘄")
  text = text.replace("x", "𝘅")
  text = text.replace("y", "𝘆")
  text = text.replace("z", "𝘇")

  text = text.replace("A", "𝗔")
  text = text.replace("B", "𝗕")
  text = text.replace("C", "𝗖")
  text = text.replace("D", "𝗗")
  text = text.replace("E", "𝗘")
  text = text.replace("F", "𝗙")
  text = text.replace("G", "𝗚")
  text = text.replace("H", "𝗛")
  text = text.replace("I", "𝗜")
  text = text.replace("J", "𝗝")
  text = text.replace("K", "𝗞")
  text = text.replace("L", "𝗟")
  text = text.replace("M", "𝗠")
  text = text.replace("N", "𝗡")
  text = text.replace("O", "𝗢")
  text = text.replace("P", "𝗣")
  text = text.replace("Q", "𝗤")
  text = text.replace("R", "𝗥")
  text = text.replace("S", "𝗦")
  text = text.replace("T", "𝗧")
  text = text.replace("U", "𝗨")
  text = text.replace("V", "𝗩")
  text = text.replace("W", "𝗪")
  text = text.replace("X", "𝗫")
  text = text.replace("Y", "𝗬")
  text = text.replace("Z", "𝗭")
  
  text = text.replace("|", "┃")
  text = text.replace("-", "━")

in ff.boldTEXT. but the text is normal when the cmd

#

is run.

frank tartan
slate swan
#

!e

a = "lol"
for element in a:
    print(f"**{element}**")
unkempt canyonBOT
#

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

001 | **l**
002 | **o**
003 | **l**
slate swan
#

or just add a start in the start and the end LOL

#

!e

a = "lol"
print(f"**{a}**")
unkempt canyonBOT
#

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

**lol**
slate swan
#

it will make it bold

frank tartan
slate swan
frank tartan
slate swan
#

!e

channelname = "coolchannelname"
print(f"**{channelname.upper()}**")
unkempt canyonBOT
#

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

**COOLCHANNELNAME**
final iron
frank tartan
# final iron What are you trying to do?

so i saw a bot that had a bold command, and it turned your text into a "bold" text, but it let you set it as channel names. (unlike regular discord bolding) I tried adding it to my code without adding too many lines to main.py, but it doesnt work

slate swan
final iron
slate swan
frank tartan
frank tartan
slate swan
#

what are you trying to do make any msg bold?

#

like a bold command and it will make everything you said bold

frank tartan
slate swan
#

and all caps?

frank tartan
final iron
slate swan
final iron
#

I mean, I just did

frank tartan
#

can yall just stop trying to prove me wrong, and help me fix it?

slate swan
#

im asking you simple questions?

final iron
slate swan
#

not the font

final iron
frank tartan
final iron
#

No because I need to see its possible

slate swan
#

oh he wants to replace each letter for a font

frank tartan
final iron
slate swan
#

well ofc that wont work

frank tartan
slate swan
#

youre setting a value then setting a new value and so on

#

!e

a = 1
a = 2
a = 3
print(a)
unkempt canyonBOT
#

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

3
slate swan
#

see only the last value is valid

frank tartan
slate swan
#

so just add numbers to each var and you will be good

frank tartan
slate swan
#

ok?

frank tartan
slate swan
#

meaning it works doesnt mean its good?

dry kelp
#
        if user.activities:
            for activity in user.activities:
                if activity.type == discord.ActivityType.listening and activity.name == "Spotify":

                    embed=discord.Embed()
                    embed.title = "**{}**".format(activity.title)
                    embed.description = "Song started at {}".format(activity.created_at.strftime("%H:%M"))
                    embed.color = activity.color
                    embed.url = "https://open.spotify.com/track/{}".format(activity.track_id)
                    embed.add_field(name="Artists", value=", ".join(activity.artists))
                    embed.add_field(name="Album", value=activity.album)
                    embed.add_field(name="Duration", value=str(activity.duration)[3:].split(".", 1)[0])
                    embed.set_thumbnail(url=activity.album_cover_url)
                    embed.set_footer(text="{} - is currently playing this song".format(user.display_name), icon_url=user.avatar.url)

                    await ctx.reply(embed=embed, mention_author=False)
slate swan
unkempt canyonBOT
#

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

001 | Traceback (most recent call last):
002 |   File "<string>", line 2, in <module>
003 | AttributeError: 'NoneType' object has no attribute 'strip'
dry kelp
#

???

final iron
dry kelp
final iron
#

!d discord.User.avatar

unkempt canyonBOT
#

property avatar: Optional[discord.asset.Asset]```
Returns an [`Asset`](https://discordpy.readthedocs.io/en/master/api.html#discord.Asset "discord.Asset") for the avatar the user has.

If the user does not have a traditional avatar, `None` is returned. If you want the avatar that a user has displayed, consider [`display_avatar`](https://discordpy.readthedocs.io/en/master/api.html#discord.User.display_avatar "discord.User.display_avatar").
slate swan
#

lol

final iron
#

Check the docs

slate swan
#

If the user does not have a traditional avatar, None is returned

dry kelp
#

ah lmfao

#

brb

final iron
#

Might be ot for this channel but if I wanted to make a welcome card what should I learn in PIL to make my ride smooth sailing?

final iron
#

Yeah

dry kelp
#
                    if user.avatar():
                        embed.set_footer(text="{} - is currently playing this song".format(user.display_name), icon_url=user.avatar.url)
                    else:
                        pass
#

do i have to use the bool?

slate swan
#

idk if its true but

dry kelp
#

it should

#

😂

#

imma give it ah test rq

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

raven pewter
#

Does this guild offer BetterDisco support

slate swan
dry kelp
#

i don't think i need a bool

tardy plume
#

how can i make my embed code can use global like i can use it on every command

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!

tardy plume
#

thx

slate swan
#

yw

#

Anyone here plays Dank Memer

#

Pls rob

dire dove
#

How do i run a script when someone joins or leaves a voice channel?

@client.event
async def ???(ctx?):
  #do stuff here
slate swan
#

i want to add buttons

#

can someone help

#

tryna use discord py 2.o

#

ive been trying for a couple hours

#

please help me

frank tartan
#

how do i upload an emoji that is in a different folder? (like a folder in the same folder main.py is in)

slate swan
#

ok but ive tryed

#

can u send me an example

#

ive been trying to get buttons for hours

#

and im really unmotiviated to try 12313 more times

#

@cedar smelt bot = commands.Bot(command_prefix=prefix,
activity=discord.Activity(type=discord.ActivityType[act].value, name=act_desc),
status=discord.Status.online)

#

this doesnt work for disnake

#

bc of (discord.activity)

#

i installed disnake btw

light violet
#

how to make a timeout cmd?

slate swan
#

which one

#

ok i changed everyhting to discord

#

@cedar smelt lets gooo

#

its great and all but

#

idk how the code works

#

so its really useless

light violet
#

wold v9 api still work?

#

ok

slate swan
#

activity not working

#

its complete dumb to use something like this when disnake already has timeouts

#

!d disnake.Member.timeout

unkempt canyonBOT
#

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

Times out the member from the guild; until then, the member will not be able to interact with the guild.

Exactly one of `duration` or `until` must be provided. To remove a timeout, set one of the parameters to `None`.

You must have the [`Permissions.moderate_members`](https://docs.disnake.dev/en/latest/api.html#disnake.Permissions.moderate_members "disnake.Permissions.moderate_members") permission to do this.

New in version 2.3.
dire dove
#

thanks! do you know how to do it using hikari?

slate swan
#

yes

#

act = "watching" # Choose one (no caps): watching, streaming, listening, playing
act_desc = "Dia+ GateKeepers" # Activity description

slate swan
#

you gotta do ```py
@GatewayBot.listen(hikari.VoiceStateUpdateEvent)

slate swan
unkempt canyonBOT
slate swan
#

use this enum instead @slate swan

#

for type kwarg

#

kk

tardy plume
#

can i make my embed as variable?

slate swan
#

(how)

#

just copy paste the exact thing

slate swan
#

this dont work???

#

no

#

ActivityType.watching

tardy plume
#

this is what happen when i make my embed as variable xd

slate swan
#

WHAT ```py
embed = discord.Embed(*kwargs)
await send(embed=embed)

tardy plume
#

kk

light violet
#

not working

@client.event
async def on_ready():
    print(f"{client.user.name} is ready to go!")

async def timeout_user(*, user_id: int, guild_id: int, until):
    headers = {"Authorization": f"Client {client.http.token}"}
    url = f"https://discord.com/api/v9/guilds/{guild_id}/members/{user_id}"
    timeout = (datetime.datetime.utcnow() + datetime.timedelta(minutes=until)).isoformat()
    json = {'communication_disabled_until': timeout}
    async with client.session.patch(url, json=json, headers=headers) as session:
        if session.status in range(200, 299):
           return True
        return False


@client.command()
async def timeout(ctx: commands.Context, member: discord.Member, until: int):
    handshake = await timeout_user(user_id=member.id, guild_id=ctx.guild.id, until=until)
    if handshake:
         return await ctx.send(f"Successfully timed out user for {until} minutes.")
    await ctx.send("Something went wrong")

it was my script btw error is coming bot object has no attribute sessions+_+ how is that

slate swan
#

just use member.timeout.....

#

you use disnake right?

light violet
#

nope

slate swan
#

move to some fork already , dpy is extremely outdated.

light violet
#

ohk

#

then can i use import disnake?

#

with discord py

slate swan
#

you use disnake instead of discord

light violet
#

what about my other cmds?

#

running on discord py

slate swan
#

just replace every discord with disnake.

light violet
#

ok

#

then should i replace the whole code discord to disnake?

slate swan
#

yea that would do the job

light violet
#

let me try

#

no module named disnake is coming+_= wow

slate swan
#

you install it first.

#

pip install disnake

light violet
#

import disnake as discord in replit

light violet
slate swan
#

go to package bar, search for disnake
and add it

light violet
#

yep

#

ok

#

from disnake.utils import find
from disnake.ext import commands, tasks

will this all too work?

#

ok

brisk brook
#
class eco(commands.Cog):
    def __init__(self,bot):
        self.bot = bot

    def num(self,number):
        num = "{:,}".format(number)
        cur = f"${num}"
        return cur

    async def open_data(self):
        with open("economy.json","r") as f:
            users = json.load(f)
        return users

    async def close_data(self, users):
        with open("economy.json","w") as f:
            json.dump(users,f)

        
        await self.close_data(users)

    async def update_wallet(self,ctx,member,op,am):
        users = await self.open_data()
        if op == "-":
            users[str(ctx.guild.id)][str(member.id)]["wallet"] -= am
        elif op ==  "+":
            users[str(ctx.guild.id)][str(member.id)]["wallet"] += am
        await self.close_data(users)
        return users[str(ctx.guild.id)][str(member.id)]["wallet"]

    @commands.command()
    @cooldown(1,20,BucketType.user)
    async def beg(self, ctx):
        user = ctx.author
        await self.open_account(ctx,user)
        users = await self.open_data()
        num = random.randrange(0,101)
        quote = [f"A stranger gives you {self.num(num)}.", f"A mysteriously man knows that you have money, but he still gives you {self.num(num)}", f"I'm poor, but I still give you {self.num(num)}", f"Stop being a beggar!! {self.num(num)}"]
        await ctx.send(random.choice(quote))
        await self.update_wallet(ctx,user,"+",num)
        await self.close_data(users)
``` Can someone tell me why the beg command won't work?
light violet
#

ok i did it and now how to make timeout cmd?

#

it worked btw thanks , btw how to make timeout

brisk brook
#

you can just use asyncio

light violet
#

ok

#

lemme try

slate swan
#

!d disnake.Member.timeout

unkempt canyonBOT
#

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

Times out the member from the guild; until then, the member will not be able to interact with the guild.

Exactly one of `duration` or `until` must be provided. To remove a timeout, set one of the parameters to `None`.

You must have the [`Permissions.moderate_members`](https://docs.disnake.dev/en/latest/api.html#disnake.Permissions.moderate_members "disnake.Permissions.moderate_members") permission to do this.

New in version 2.3.
slate swan
#

the duration will be in seconds

light violet
#

how to convert to mins

#

*?

brisk brook
#

that'll be more complicated

#

simply use a calculator to convert minutes into seconds

light violet
#
@client.command()
@disnake.ext.commands.has_permissions(manage_nicknames=True)
async def timeout(ctx, member: disnake.Member,time: float, *, reason=None) -> None:
    await member.timeout(duration=time, reason=reason)
    await ctx.send(f"{member.mention} has been timed out for {time} Seconds, With the reason of {reason}")```
quick gust
#

channel is none

light violet
#

abe proton+_= kaha se mila bro rao ka proton hai kya

frank tartan
#

how do i upload an emoji that is in a different folder? (like a folder in the same folder main.py is in)

plush pebble
quick gust
#

await channel.send() here the channel is returning None

light violet
#

@slate swan@cedar smelt it worked thanks

brisk brook
#

you can add this if you want

#

or something along these lines

light violet
#

;