#discord-bots

1 messages · Page 778 of 1

fresh orchid
#

Is this the right channel for the problem?

potent spear
fresh orchid
#

ok

potent spear
#

I'll show you this

#

maybe that'll help

#
for key,value in data_dict.items():
  print(f"message_id_string is {key}, messages_count is {value['messages']}")```
fresh orchid
#

Thx I'll try

potent spear
#

not in the mood to copy ofc

tidal hawk
#

How can I set slash registration to be local inside Cog

#

i tried making it local from main.py but it didn't work

#

do i define new bot?

slate swan
cold sonnet
#

just think about it brotha

#

if you define new bot

#

and put commands inside new bot

#

old bot won't have those commands

#

and since you can only run one bot

#

you either won't have old bot or new bot

tidal hawk
#

Yeah that was a stupid guess

slate swan
# tidal hawk do i define new bot?

supply the bot variable to te cog a basic cog structure ```py
class MyCog(commands.Cog):
def init(self , bot):
self.bot = bot

def setup(bot):
bot.add_cog(MyCog(bot))```

tidal hawk
#

Just tried creating local registration for slash commands, but it doesn't work

slate swan
#

you get this if you understand what __init__ is and how oop works

#

Ah

#

For slash?

tidal hawk
#

Mhm

slate swan
#

What library are you using

tidal hawk
#

disnake

slate swan
#

use commands.slash_command

#

Just like you use commands.command instead of bot.command in cogs
bot.slash_command is commands.slash_command

tidal hawk
#

Tried it a while ago:

#

it doesn't show up in guild

slate swan
#

cof cof

#

in main file it's bot.slash_command

#

not commands.slash_command

tidal hawk
slate swan
tidal hawk
#

it was in cog

slate swan
slate swan
#

:)

slate swan
tidal hawk
#

Got too used to pycharm, it used to self by itself :(

#

Gives me error: Failed to overwrite commands due to missing access, but the bot has all of the permissions

slate swan
#

you didn't invite it with application command scope

slate swan
slate swan
slate swan
#

random person : i get this error
Ashley : cry about it with a hug emoji

#

😂

tidal hawk
#

comedy peak

slate swan
#

let's not start an ot chat hehe , the channel is being a bit off topic these days

tender estuary
slate swan
#

imo, sure

velvet tinsel
tender estuary
#

Because I did and now I am messed up

#

Probably gotta get hang of it first

slate swan
#

well if you don't like learning everything from scratch. Use a fork instead

velvet tinsel
#

a fork of dpy?

slate swan
slate swan
manic wing
#

use disnake so you can have access to disnake-debug

velvet tinsel
slate swan
#

probably disnake

manic wing
slate swan
#

Indeed

velvet tinsel
#

yes disnake 💪

manic wing
#

yes disnake-debug 💪

slate swan
velvet tinsel
#

imo disnake is a pretty great fork of danny's dpy, unlike Pycord pithink

slate swan
#

Danny doesn't like pycord himself.

velvet tinsel
#

when

velvet tinsel
ashen notch
#

Play nice or hush

slate swan
manic wing
velvet tinsel
#

I don't have friends

slate swan
#

Most of the people here won't prefer hikari

#

but i use it ¯\_(ツ)_/¯

manic wing
ashen notch
#

You guys think it's going to circle back around to there being one big one or do you think it'll end up like Linux distros? Too many flavors, not enough substance

manic wing
#

i need to go insult him in the jss

velvet tinsel
manic wing
velvet tinsel
slate swan
manic wing
velvet tinsel
velvet tinsel
slate swan
#

there are people who prefer other libraries like hikari or pincer too

slate swan
#

which one of these forks has a decent cache?

#

so tired of dpys cache lol

maiden fable
#

forks have the dpy cache only lol

slate swan
maiden fable
#

they are "dpy forks"

slate swan
#

But hikari does have better cache impl for sure

#

does hikari have a proper cache?

#

yes , and it's upto 2x faster :)

velvet tinsel
slate swan
#

Time to migrate to hikari then lol

maiden fable
velvet tinsel
slate swan
velvet tinsel
#

I haven't really worked on my discord python project pithink but then again, I'll have to make it as terrible as possible, hence the name "trashcord"

slate swan
#

dekriel,let's not talk about the time you take to do things

velvet tinsel
#

it doesn't have async, let alone def. I'm gonna make this a nightmare for discord bot developers 💀

velvet tinsel
slate swan
#

4810peepohands the emojis for jarvide , you made us wait forever

velvet tinsel
#

I never realized you were Sasuke

slate swan
#

Sarthak*

velvet tinsel
slate swan
#

Hehe

velvet tinsel
#

ok

manic wing
manic wing
velvet tinsel
#

apart from a few people

slate swan
#

the few people are literal "gods"

manic wing
modern fiber
#

Sends only first word as reason uh? This is the code.

manic wing
#

ropra is the only one who works on it lol

modern fiber
#

I did .kick user being ultra cool

slate swan
#

why stopped with the development?

manic wing
velvet tinsel
modern fiber
manic wing
manic wing
velvet tinsel
modern fiber
manic wing
#

as if dekriel can help xD

velvet tinsel
modern fiber
manic wing
tender estuary
#

Ethical concerns..

tender estuary
modern fiber
modern fiber
tender estuary
#
async def test(ctx, *, reason=None)
tender estuary
#

Key word argument

manic wing
velvet tinsel
manic wing
#

maybe this is why you aren't good at coding

tender estuary
#

Visual studio is NOT an IDE

#

its a text editor

maiden fable
#

Hey BTW since I got an i3 11th gen, should I use PyCharm or use VSC only 🤔

modern fiber
velvet tinsel
tender estuary
modern fiber
tender estuary
tidal hawk
#

Broo I invited the bot with these scopes, but it still gives me error: SyncWarning: Failed to overwrite commands Missing access after trying to create local slash

tender estuary
#

I have a doubt, do you put the * before the reason because every character of the reason we give is stored as a character and not a string?

#

because if it is stored as a string why use *

modern fiber
#

Like this?

tender estuary
tender estuary
sage otter
modern fiber
velvet tinsel
manic wing
#

sorry i took a shit halfway through writing that

sage otter
velvet tinsel
velvet tinsel
sage otter
#

You added the most self explanatory comments

#

# google command
Well obviously. Anyone reading can determine that.

#

Why didn’t you actually comment on the code inside the commands. And describe those instead.

modern fiber
#

Do I state perms like

#

kick_member or kick_members

compact ruin
#

Guys i have a problemo

#

I am unable to import Discord ui

#

The requirements are already satisfied

slate swan
compact ruin
slate swan
#

did you install it using gitbhub link?

compact ruin
#

Trying to learn how to make buttons but the imports pickin a fight

#

Nah

#

I installed using pip

slate swan
#

the official version isnt on pypi yet, use the github link to install it

compact ruin
#

py -m pip install discord-ui
is what i used

compact ruin
maiden fable
slate swan
#

^^

maiden fable
#

Hmm I wrote that link myself rip

slate swan
maiden fable
#

!pypi discord-ui

unkempt canyonBOT
compact ruin
#

Ah i see

maiden fable
#

Rip

slate swan
#

¯_(ツ)_/¯

exotic bear
# unkempt canyon

you should probably just use py-cord if you're gonna need to install a module for every other discord feature

slate swan
#

ahem ahem p-pycord?

#

who is that?

exotic bear
#

which all the latest fancy features

slate swan
#

cof cof

exotic bear
#

yea like slash commands and stuff

compact ruin
#

How do i install the git sadboi

exotic bear
#

why is everyone acting weird did i do something wrong

slate swan
compact ruin
#

I don't usually deal with the git sadboi

slate swan
exotic bear
#

!pypi disnake

unkempt canyonBOT
compact ruin
#

Tried that and got an error

exotic bear
#

i think its pip install git+githublink

maiden fable
compact ruin
#

ERROR: Cannot unpack file

compact ruin
slate swan
#

cry about it 🫂

exotic bear
#

can u send screenshot

quick gust
exotic bear
#

i see

slate swan
quick gust
#

agreed!

slate swan
#

totally not sponsored

exotic bear
#

disnake more like

compact ruin
exotic bear
#

disnake is

slate swan
exotic bear
#

yes

#

that

compact ruin
#
ERROR: Cannot unpack file C:\Users\Alpha\AppData\Local\Temp\pip-unpack-ee_ifn8s\discord.py (downloaded from C:\Users\Alpha\AppData\Local\Temp\pip- 
  req-build-g3xagh_i, content-type: text/html; charset=utf-8); cannot detect archive format
ERROR: Cannot determine archive format of C:\Users\Alpha\AppData\Local\Temp\pip-req-build-g3xagh_i
#

@exotic bear

exotic bear
compact ruin
slate swan
exotic bear
slate swan
#

2.0 isnt on PyPi yet

exotic bear
#

oh

slate swan
#

yep

exotic bear
#

nvm then

slate swan
#

its alright, I'll save you further humiliation and not talk about it

exotic bear
#

they still update dpy?? lemon_blush

exotic bear
#

then how is there a version 2?

compact ruin
#

sadboi Is it okay to throw my pc out the window

slate swan
slate swan
exotic bear
compact ruin
slate swan
#

it wont be continued anymore

#

at least not as of now

exotic bear
slate swan
exotic bear
#

it's gonna cancel two of my bot's beloved features

slate swan
potent spear
#

which are? (the "beloved features")

exotic bear
compact ruin
#

A H H H H H H H H

exotic bear
compact ruin
potent spear
slate swan
maiden fable
exotic bear
compact ruin
potent spear
compact ruin
#

WHY JUST WHY

maiden fable
slate swan
#

otherwise hunter uwu forever

maiden fable
#

Then join us

slate swan
compact ruin
maiden fable
#

old laptops' death ceremony

slate swan
exotic bear
compact ruin
maiden fable
#

@compact ruin sometimes doing pip install git+https://github.com/Rapptz/discord.py.git works (I suffixed .git)

slate swan
#

anyways

#

.topic

lament depotBOT
#
**What feature would you be the most interested in making?**

Suggest more topics here!

maiden fable
#

Imagine VSC and Chrome with tensorflow running on 1.7 GHz

compact ruin
river flare
#

hello. I import my config like this, but get this error ```python
with open('./config.json', 'r') as cjson:
config = json.load(cjson)

UnicodeDecodeError: 'charmap' codec can't decode byte 0x9f in position 1428: character maps to <undefined>

compact ruin
#

sadboi Pretty sure i have Git installed

maiden fable
#

U didn't add it to path

peak loom
#

This won't work

slate swan
#

🚶just install some fork.

exotic bear
slate swan
maiden fable
slate swan
#

8 GBS of ram ( cries in 4)

maiden fable
#

RIP I hate Anti Virus now

maiden fable
slate swan
#

ahrixjam Even my phone has more memory storage than my laptop

slate swan
compact ruin
maiden fable
#

I am using Windows 11 currently, and have youtube and discord opened and Spotify in background, so that isn't a bad usage

maiden fable
slate swan
exotic bear
maiden fable
#

Eh, I got a new laptop and 8 gigs was enough for me anyways

slate swan
#

Ayo, how do I import {} from a json file into a code ?

@client.command()
async def test(ctx):

    with open("file", "r") as file1:
        test = json.load(file1)
    
    await ctx.send(test)
fresh orchid
#

so I have this json file and now I used this code to print the fivebiggest message amounts


        leaderboard = []
        for key,value in users.items():
        
            leaderboard.append(value['messages'])
        leaderboard.sort(reverse=True)
        print(leaderboard[0])  
        print(leaderboard[1]) 
        print(leaderboard[2])
        print(leaderboard[3])
        print(leaderboard[4])

So I just have five numbers after that
Is there any way to the id again with that number
Or is there a way where I can sort the messages amounts and keep the ids with them?

slate swan
maiden fable
#

damn I can hear the fans

slate swan
#

!d json.load

unkempt canyonBOT
#

json.load(fp, *, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw)```
Deserialize *fp* (a `.read()`-supporting [text file](https://docs.python.org/3/glossary.html#term-text-file) or [binary file](https://docs.python.org/3/glossary.html#term-binary-file) containing a JSON document) to a Python object using this [conversion table](https://docs.python.org/3/library/json.html#json-to-py-table).

*object\_hook* is an optional function that will be called with the result of any object literal decoded (a [`dict`](https://docs.python.org/3/library/stdtypes.html#dict "dict")). The return value of *object\_hook* will be used instead of the [`dict`](https://docs.python.org/3/library/stdtypes.html#dict "dict"). This feature can be used to implement custom decoders (e.g. [JSON-RPC](http://www.jsonrpc.org) class hinting).

*object\_pairs\_hook* is an optional function that will be called with the result of any object literal decoded with an ordered list of pairs. The return value of *object\_pairs\_hook* will be used instead of the [`dict`](https://docs.python.org/3/library/stdtypes.html#dict "dict"). This feature can be used to implement custom decoders. If *object\_hook* is also defined, the *object\_pairs\_hook* takes priority.
compact ruin
slate swan
maiden fable
#

At least I got a SSD in the laptop, so it isn't that slow

maiden fable
dire scaffold
#

ello

slate swan
maiden fable
#

The older one had about 200 gigs HDD, soooooo

slate swan
maiden fable
#

Hmmmmmmm facts

dire scaffold
#

Can you say me whats the error?

slate swan
maiden fable
#

LMAO

slate swan
#

Remove that one with discord.Client()

compact ruin
#

Is there a reason it wont let me use git clone on vsc sadboi

#

Do i need to install git separately-?

slate swan
#

Yep

compact ruin
slate swan
#

ofcourse

compact ruin
#

sadboi I hate you github

slate swan
#

why don't you use the command hunter sent?

#

pip install git+... One

compact ruin
dire scaffold
compact ruin
#

did not work sadboi

honest shoal
dire scaffold
#

no

#

this is js

cloud dawn
compact ruin
#

sadboi This is just annoying i cant clone the git

cloud dawn
dire scaffold
#

thats old token

fresh orchid
#
{"695229647071015040": {"messages": 17639}, "618341493932266506": {"messages": 318}, "884402383523339295": {"messages": 1334}
for key,value in data.items():
            
            print(f"{key}     {value['messages']}")

So I have a json file like this and the code you see here. When I run it I get outputs like

767385286614319134     3120
768843832782618644     3

Now I want to sort them by the message number. How can I do this without removing the id or is there a way to sort it without id and get the id later again

If this isnt the right channel just say which one is right

dire scaffold
#

i have do in another code and it's still error

slate swan
dire scaffold
#

Ummm i deleted but is now another big error

slate swan
#
# Setting `Playing ` status
await bot.change_presence(activity=discord.Game(name="a game"))

# Setting `Streaming ` status
await bot.change_presence(activity=discord.Streaming(name="My Stream", url=my_twitch_url))

# Setting `Listening ` status
await bot.change_presence(activity=discord.Activity(type=discord.ActivityType.listening, name="a song"))

# Setting `Watching ` status
await bot.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name="a movie"))```
#

"Text"+cmd to f"text {cmd}"

#

Since you have more overview, I see again twice client

#

That's all I see

#

Check your token again

slate swan
#

!e

a = None
print(a.strip(" "))
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'
dire scaffold
#

and how do i put?

slate swan
#

the heck are you trying to do

dire scaffold
#

a discord bot

slate swan
#

i ment the syntax

maiden fable
#

oki

slate swan
#

ofc i know youre making a discord bot

maiden fable
slate swan
dire scaffold
#

oop

slate swan
#

!e

new list = ["element", "element"]
print(new list)
unkempt canyonBOT
#

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

001 |   File "<string>", line 1
002 |     new list = ["element", "element"]
003 |         ^^^^
004 | SyntaxError: invalid syntax
slate swan
slate swan
#

It's not js :3

slate swan
#

which dont affect run time

#

Non code text

#

comments*

#

did u say smth

dire scaffold
slate swan
#

lmfao

slate swan
dire scaffold
#

yeah

slate swan
dire scaffold
#

ok tnks

slate swan
#

yw

fresh orchid
#
leaderboard.append(f"{key} {value['messages']}")
            leaderboard.sort(reverse=True)

How can I "ignore" key and just sort value?

maiden fable
#

Wym

potent spear
river flare
#

hello! I have this button which i want to have a custom emoji as an icon. But i get this```python
(label=f":phantomaki:", style=nextcord.ButtonStyle.gray)

fresh orchid
potent spear
marble rampart
#

hey

#

someone need help ?

marble rampart
#

i think there is an emoji arg

marble rampart
#

like (emoji=":phantomaki:")

velvet tinsel
#

for example

#

there, ID shit

#

@river flare pithink

#

it actually says on the button the ID so you can just c&p

river flare
slate swan
lofty cedar
#

Could someone help?

@client.command()
async def weather(ctx):
    diceRoll = random.randint(1,100)
    currentWeather = ""
    if 1 <= diceRoll <= 3:
        currentWeather = "Stormy"
        await ctx.send("It's a storm! But don't fear, it's not flooding.")
    if 4 <= diceRoll <= 10:
        currentWeather = "Heavy fog"
        await ctx.send("Heavy fog has decended upon you!")
    if 11 <= diceRoll <= 18:
        currentWeather = "Light fog"
        await ctx.send("Light fog has decended upon you!")
    if 19 <= diceRoll <= 47:
        currentWeather = "Sunny"
        await ctx.send("The sun is shining down onto you!")
    if 48 <= diceRoll <= 79:
        currentWeather = "Cloudy"
        await ctx.send("Clouds start to cover the sky.")
    if 80 <= diceRoll <= 89:
        currentWeather = "Light rain"
        await ctx.send("A light drizzle has started.")
    if 90 <= diceRoll <= 93:
        currentWeather = "Heavy rain (flooding)"
        await ctx.send("Heavy rain has started falling and the world is flooding fast!")
    if 94 <= diceRoll <= 100:
        currentWeather = "Strong winds"
        await ctx.send("The wind is starting to pick up and is getting strong.")

@client.command()
async def weatherCurrently(ctx):
    currentWeather = currentWeather
    print(currentWeather)

I'm trying to make it print the variable currentWeather in the terminal but it says it's not defined.

final iron
#

You cannot access it like that

slate swan
#

elif is a thing

final iron
#

Also, you should check out pep8

slate swan
final iron
#

Fuck that limit

slate swan
#

isnt it 72 for max line

final iron
#

Seems too little

slate swan
#

i follow the max line

#

rule and i get hated for it lol

final iron
#

¯\_(ツ)_/¯

slate swan
final iron
slate swan
#

bruh hold up

velvet tinsel
slate swan
final iron
#

Wtf

#

How can you read that

slate swan
#

got to follow it bropithink

final iron
#

That's why I don't follow it

#

Actually makes some shit unreadable

slate swan
#

you have to😤

#

like me👁️ 👁️

final iron
#

No

manic wing
#

okimii

final iron
#

I refuse

manic wing
#

i follow black, and black follows pep-8 right?

round robin
#

how do i get the first channel in a server?

potent spear
#

don't tell me that's pep8

slate swan
velvet tinsel
#

Idk if it’s my phone or it looks weird

slate swan
manic wing
slate swan
potent spear
#

aight, it better not be

manic wing
#

okimii you think thats what pep-8 is, but it just isnt

velvet tinsel
slate swan
#

if i do it the black way it will still break the max line rule

next wing
#

can i get some help with a command for my discord bot in #help-carrot

manic wing
slate swan
#

how would it work theres not specification

round robin
#

how do i get the first channel in a server?

velvet tinsel
#

Okimii I feel like you’re doing too many lines for a command

velvet tinsel
manic wing
#

so black and some random python formatter

vale wing
round robin
velvet tinsel
round robin
#

It

manic wing
#

and some other random one also formats it to ```py
@command(aliases=["kickhammer", "userkick", "memberkick", "banmember", "banuser"])
async def kick(
self, ctx: Context, member: Member, *, reason: str = "No Reason Provided"
) -> Optional[Message]:
if ctx.author.id == member.id:
return await ctx.send(f"{ctx.author.mention} you cannot ban yourself")
await ctx.send(
f"Would you like to kick {member.mention}",
view=KickConfirmation(ctx.author, member, reason),
)

vale wing
#

!d discord.TextChannel.position

unkempt canyonBOT
dire dove
#

I'm trying to send a message to a user and have it time out after 30 seconds or so, how do I do that?


    await ctx.send(f"Challenging {p2.name}!")
    p2_msg = await p2.send(f"{p1.name} is challenging you to a battle! Do you accept?")
    await p2_msg.add_reaction("✅")
manic wing
unkempt canyonBOT
#

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

Waits for a WebSocket event to be dispatched.

This could be used to wait for a user to reply to a message, or to react to a message, or to edit a message in a self-contained way.

The `timeout` parameter is passed onto [`asyncio.wait_for()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.wait_for "(in Python v3.10)"). By default, it does not timeout. Note that this does propagate the [`asyncio.TimeoutError`](https://docs.python.org/3/library/asyncio-exceptions.html#asyncio.TimeoutError "(in Python v3.10)") for you in case of timeout and is provided for ease of use.

In case the event returns multiple arguments, a [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.10)") containing those arguments is returned instead. Please check the [documentation](https://docs.disnake.dev/en/latest/api.html#discord-api-events) for a list of events and their parameters.

This function returns the **first event that meets the requirements**...
velvet tinsel
#

!d asyncio.TimeoutError for timeout

unkempt canyonBOT
#

exception asyncio.TimeoutError```
The operation has exceeded the given deadline.

Important

This exception is different from the builtin [`TimeoutError`](https://docs.python.org/3/library/exceptions.html#TimeoutError "TimeoutError") exception.
velvet tinsel
#

if you want to catch it pithink

final iron
#

Is there a more elegant way to get user input than wait_for?

slate swan
velvet tinsel
final iron
#

Damn

vale wing
#

No unless you create your own

velvet tinsel
final iron
#

A text box would be very nice

#

Where you can type

velvet tinsel
#

😔

vale wing
#

I remember discord was talking about something like that

manic wing
#

pep-8 is supposed to be readable, presentable and efficient. this is hardly readable, and its inefficient through its usage of lines

velvet tinsel
#

Would be pretty cool if you could send commands to the bot via VC 😳

slate swan
manic wing
velvet tinsel
final iron
#

Discord bots get send voice packets iirc

manic wing
#

wait

#

fuck wrong command

dire dove
#

@manic wing @velvet tinsel so

try:
  bot.wait_for(on_reaction, *, check=None, timeout = 30)
  await ctx.send("You accepted the challenge!")

except asyncio.TimeoutError:
  await ctx.send("You did not accepted the challenge!")
final iron
#

Then you can use a speech to text library

unkempt canyonBOT
#

The snippet you tried to send was too long. Please see #bot-commands for the full snippet.

final iron
#

And trigger the event

manic wing
#
await thebed(ctx, '', '**Error: **distance must be an integer (an index placevalue) if no `author_from` is given!') if hasattr(distance, 'upper') and author_from is None else await thebed(ctx, '', f'*`{distance}`*: "{data["feedback"]["message"][distance]}", submitted by **{data["feedback"]["author"][distance]}**' if distance != 0 else f'**You can index off of the index on the left side. Type `{ctx.prefix}viewfeedback <index>`\n**\n' + "\n".join([f"`{num}:` {data['feedback']['message'][k]}**, said by {data['feedback']['author'][k]}**" for num, k in enumerate(range(len(data['feedback']['message']))) if num <= 9]), a='Feedback', i_u=ctx.author.avatar.url) if author_from is None else await thebed(ctx, '', f'\n'.join([f"`{num}`: {data['feedback']['message'][num]}" for num, k in enumerate(data['feedback']['author']) if k ==author_from]), a=f'Feedback from {author_from}', i_u=ctx.author.avatar.url, f=f'All these messges are from {author_from}') if hasattr(author_from, 'upper') else await thebed(ctx, '', f'\n'.join([f"`{num}`: {data['feedback']['message'][num]}" for num, k in enumerate(data['feedback']['id']) if k ==author_from]), a=f'Feedback from {await self.bot.fetch_user(author_from)}', i_u=ctx.author.avatar.url, f=f'All these messages are from {await self.bot.fetch_user(author_from)}')
``` all one line
manic wing
final iron
#

Ever heard of readability?

manic wing
#

this is just ott

manic wing
vale wing
#

This is pretty readable wdym troll

manic wing
#

you can make a bot with commands and run it in all one line

slate swan
#

idk this way seems readable to me👁️ 👁️

potent spear
#

if you're blind...

manic wing
#

^

round robin
slate swan
#

no👁️ 👁️

vale wing
slate swan
dire dove
round robin
#

That is

vale wing
#

@round robin iirc to get the list sorted by position you need to do something like

sorted_list = sorted(guild.text_channels, key=lambda c: c.position)
first_channel = sorted_list[0]```
manic wing
#
(_:=lambda __: __import__('dotenv').load_dotenv);(bot:=__import__('disnake.ext.commands').Bot(command_prefix='_', ...)).run(_((__:=True or False)); __import__('os').dotenv['TOKEN'])```
#

create bot and run it in one line

#

im sure you can add commands

round robin
#

What's iirc

manic wing
#

if i recall correctly

vale wing
#

If I remember correctly

manic wing
#

*recall

vale wing
#

Two versions

manic wing
#

you win

vale wing
#

We both do

manic wing
#

no fun

vale wing
manic wing
#

theres prob a way around it

vale wing
#

Maybe define a Command and just add_command

manic wing
#

add_command requires Command to be decorated

#

i believe

lofty cedar
vale wing
#

I mean

#

!d discord.ext.commands.Command

unkempt canyonBOT
#

class discord.ext.commands.Command(*args, **kwargs)```
A class that implements the protocol for a bot text command.

These are not created manually, instead they are created via the decorator or functional interface.
manic wing
#

@vale wing

unkempt canyonBOT
#

disnake/ext/commands/core.py line 1626

if cls is MISSING:```
manic wing
#

simple

slate swan
#

discord.ext.commands.errors.CommandInvokeError: Command raised an exception: HTTPException: 400 Bad Request (error code: 50006): Cannot send an empty message

The embed is not empty

#

@client.command()
async def test(ctx):
await ctx.message.delete()
embed = discord.Embed(title='test')
await ctx.send(embed=embed)

cold sonnet
#

try putting a description

#

@slate swan

slate swan
#

its still the same

cold sonnet
#

with a description?

slate swan
#

ya

#

@client.command()
async def test(ctx):
await ctx.message.delete()
embed = discord.Embed(title='test', description='ok')
await ctx.send(embed=embed)

#

import discord

bot=discord.ext.commands.Bot(command_prefix=commands.when_mentioned_or(None))

#

👁️

pine verge
#

is it possible to start two discord bots from one file ?

cold sonnet
#

yeah that might be messed up

slate swan
pine verge
slate swan
slate swan
#

still the same for some reason

cold sonnet
slate swan
unkempt canyonBOT
#

discord.ext.commands.when_mentioned(bot, msg)```
A callable that implements a command prefix equivalent to being mentioned.

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

discord.ext.commands.errors.CommandInvokeError: Command raised an exception: ValueError: parameters are of unsupported type

Why do I get this error with

await ctx.send("Becka's Boutique Card Info:\n----------------\nName: " + row[0] + " \nAccountID: " + row[1] + "\nAccount Balance: " + row[2] + "")

cold sonnet
#

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

slate swan
#

its a old tag from discord.py server ( they removed it now)

dire dove
#
    await ctx.send(f"{p1.name} has started a typing contest!")

    await ctx.send(f"Challenging {p2.name}!")
    p2_msg = await p2.send(f"{p1.name} is challenging you to a battle! Do you accept?")
    await p2_msg.add_reaction("✅")

    def check(reaction, user):
        return user == p2 and str(reaction.emoji) == '✅'


    try:
        reaction, user = await client.wait_for('reaction_add', timeout=30.0, check=check)
    except asyncio.TimeoutError:
        await p2.send("You have declined the challenge")
        await ctx.send(f"{p2.name} has declined the challenge!")
    else:
        await p2.send("You have accepeted the challenge!")
        await ctx.send(f"{p2.name} has accepted the challenge!")

i'm trying to detect when a user reacts with ✅ , but it's not detecting, even when the user tries un-reacting and reacting again

pine verge
quaint epoch
#

i had the same problem A LOT

#
 await ctx.send(f"{p1.name} has started a typing contest!")

    await ctx.send(f"Challenging {p2.name}!")
    p2_msg = await p2.send(f"{p1.name} is challenging you to a battle! Do you accept?")
    await p2_msg.add_reaction(":white_check_mark:")

    def check(reaction, user):
        return user == p2 and str(reaction.emoji) == ':white_check_mark:'


    try:
        reaction, user = await client.wait_for('raw_reaction_add', timeout=30.0, check=check)
    except asyncio.TimeoutError:
        await p2.send("You have declined the challenge")
        await ctx.send(f"{p2.name} has declined the challenge!")
    else:
        await p2.send("You have accepeted the challenge!")
        await ctx.send(f"{p2.name} has accepted the challenge!")```
weary mirage
# cold sonnet !f-strings

okay, I did this
await ctx.send(f"Becka's Boutique Card Info:\n----------------\nName: {row[0]} \nAccountID: {row[1]} \nAccount Balance: {row[2]}")
and I still get the error
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: ValueError: parameters are of unsupported type

cold sonnet
#

is the error really in this line

slim ibex
#

obv not

#

Is row a param in the function?

weary mirage
#

oh goddd

#

okay wait, my apologies

#

it's something else

flat solstice
#

So I've seen this nonce (int) – The nonce to use for sending this message. If the message was successfully sent, then the message will have a nonce with this value. in the dpy docs (https://discordpy.readthedocs.io/en/latest/api.html?highlight=dm#discord.DMChannel) but i'm not sure how to use it. Does this mean my bot will know when a message doesn't get sent (i.e. if it tries to send a message to someone's DMs but they have them closed so it errors) because that seems like something I would find incredible useful for when my DM on_member_join doesn't get sent, I can just redirect it to a channel instead. ik I should catch these kinds of error's in on_error in a error handler but i'm not doing that (yet anyway)

Also is it possible for the bot to know if the user has their DMs closed? So I can say "if member.dm.closed send join dm to channel else send to dm"

slim ibex
#

!d isinstance

unkempt canyonBOT
#

isinstance(object, classinfo)```
Return `True` if the *object* argument is an instance of the *classinfo* argument, or of a (direct, indirect, or [virtual](https://docs.python.org/3/glossary.html#term-abstract-base-class)) subclass thereof. If *object* is not an object of the given type, the function always returns `False`. If *classinfo* is a tuple of type objects (or recursively, other such tuples) or a [Union Type](https://docs.python.org/3/library/stdtypes.html#types-union) of multiple types, return `True` if *object* is an instance of any of the types. If *classinfo* is not a type or tuple of types and such tuples, 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).
slim ibex
#

You can use this to check if the channel is a dm channel

dire dove
cold sonnet
#

or if message.guild is None

slim ibex
#

^

dire dove
#

@quaint epoch figured it out, i had to do channel.send instead of sending it in a dm

weary mirage
flat solstice
slim ibex
#

I believe so

weary mirage
#
async def bbgc(ctx):
    id = ctx.author.id
    for row in cur.execute("SELECT * FROM bbgc WHERE playerid = (?)", [id]):
        await ctx.send("Hello")
        await ctx.send(f"Becka's Boutique Card Info:\n----------------\nName: {row[0]} \nAccountID: {row[1]} \nAccount Balance:  {row[2]}")```
I'm just so fucking confused now, this won't work

```ValueError: parameters are of unsupported type```
is the error I'm getting
slim ibex
#

that is a weird query

#

!d discord.DMChannel @flat solstice

unkempt canyonBOT
#

class discord.DMChannel```
Represents a Discord direct message 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 a string representation of the channel
weary mirage
#

tf do I do 😭

pine verge
#
loop.create_task(client2.start(TOKEN))
client.run(TOKEN)

what difference does it make if i swap the clients ? how will the logic work

#

im not very familiar with asyncio and discord py

slim ibex
#

Don’t run 2 clients at the same time

#

no point in doing so anyways

#

Just make two separate projects

pine verge
#

but can you explain how does run differ from start

#

or like how will it change if i swap the order\

slim ibex
#

!d asyncio.create_task

unkempt canyonBOT
#

asyncio.create_task(coro, *, name=None)```
Wrap the *coro* [coroutine](https://docs.python.org/3/library/asyncio-task.html#coroutine) into a [`Task`](https://docs.python.org/3/library/asyncio-task.html#asyncio.Task "asyncio.Task") and schedule its execution. Return the Task object.

If *name* is not `None`, it is set as the name of the task using [`Task.set_name()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.Task.set_name "asyncio.Task.set_name").

The task is executed in the loop returned by [`get_running_loop()`](https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.get_running_loop "asyncio.get_running_loop"), [`RuntimeError`](https://docs.python.org/3/library/exceptions.html#RuntimeError "RuntimeError") is raised if there is no running loop in current thread.

This function has been **added in Python 3.7**. Prior to Python 3.7, the low-level [`asyncio.ensure_future()`](https://docs.python.org/3/library/asyncio-future.html#asyncio.ensure_future "asyncio.ensure_future") function can be used instead...
slim ibex
#

!d discord.Client.run

unkempt canyonBOT
#

run(*args, **kwargs)```
A blocking call that abstracts away the event loop initialisation from you.

If you want more control over the event loop then this function should not be used. Use [`start()`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client.start "discord.Client.start") coroutine or [`connect()`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client.connect "discord.Client.connect") + [`login()`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client.login "discord.Client.login").

Roughly Equivalent to...
slim ibex
#

the client.run creates the event loop for you

flint quartz
#

Hi

river flare
#

hellow huys. I have these two buttons but i want to make them, when you click one individually, to change the name of the button to the amoji + the total clicks. How can i do that?```python
@nextcord.ui.button(label=f":white_check_mark:", style=nextcord.ButtonStyle.gray)
async def Question1(self, button: nextcord.ui.Button, interaction: nextcord.Interaction):
user = interaction.user
emb=nextcord.Embed(title=":white_check_mark: Approved Suggestion", description=f"Ευχαριστούμε για την γνώμη σου!", color=0x00FF00, timestamp=datetime.now())
emb.set_author(name=user.name, icon_url=user.avatar.url)
await interaction.response.send_message(embed=emb, ephemeral=True)

    @nextcord.ui.button(label=":x:", style=nextcord.ButtonStyle.gray)
    async def Question(self, button: nextcord.ui.Button, interaction: nextcord.Interaction):
            user = interaction.user
            emb=nextcord.Embed(title=":x: Rejected Suggestion", description=f"Ευχαριστούμε για την γνώμη σου!", color=0xFF0000, timestamp=datetime.now())
            emb.set_author(name=user.name, icon_url=user.avatar.url)
            await interaction.response.send_message(embed=emb, ephemeral=True)
flat solstice
#

How can I check who adds a reaction to a message?

quaint scaffold
quaint scaffold
unkempt canyonBOT
#

discord.on_raw_reaction_add(payload)```
Called when a message has a reaction added. Unlike [`on_reaction_add()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_reaction_add "discord.on_reaction_add"), this is called regardless of the state of the internal message cache.

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

also if i'm doing a wait_for(raw_reaction_add it would be self.bot.wait_for right?

quaint scaffold
#

Yes

quaint scaffold
#

Assuming it's in a class / cog, if you used bot it would error out and say it's not defined

slate swan
#

if self.bot = bot then yes

echo pivot
#

Hello, I have made a discord bot using replit, it sends messages to a server at a certain time.
But for seemingly no reason, the bot goes offline after sending the first two messages. The code is still running in replit and no errors occured.

slate swan
#

show the code

echo pivot
#
from discord.ext import commands, tasks
import os
import json
import pytz
from pathlib import Path
from datetime import datetime
from server import serve
from tasks import task 

names = os.environ
is_running = False
local_tz = pytz.timezone('region')
current_time = datetime.now(local_tz).strftime("%B %-d - %-I:%M%p")

client = commands.Bot(command_prefix = '-')

@client.event
async def on_ready():
  print(f'[{current_time}] {client.user} has started.')

@client.command(aliases=['init'])
async def start(ctx, *, sent_data):
  data = json.loads(Path('tasks.json').read_text())

  for item in data:
    for param in sent_data.replace('`', '').split(','):
      param = param.strip().split('=')
      if item['id'] == param[0]:
        item['user'] = param[1]

  track.start(ctx, data)
  
  await ctx.channel.send('Running...')

@client.command()
async def clear(ctx, amount=5):
  await ctx.channel.purge(limit=amount + 1)

@tasks.loop(seconds=60)
async def track(ctx, data):
  # Get current date and time
  current_time = datetime.now(local_tz).strftime("%-I:%M%p")
  day = datetime.now(local_tz).strftime("%-w")

  for active in data:
    if current_time == active['time'] and day in active['days']:
      print(f"Executing task: '{active['id']}' at {current_time}")
      user = await task(
        active['time'],
        active['sequence'],
        active['user'],
        active['message'],
        f'<@&{active["ping"]}>',
        client.get_channel(active['channel']),
        names
      )

      active['user'] = str(user)

serve()
client.run(names['token'])
#

tasks.py

import os
import pytz
from datetime import datetime

async def task(set_time, sequence, sequence_current, msg, ping_user, channel, keys):
  datetime_now = datetime.now(pytz.timezone('America/Vancouver')).strftime("%A, %B %-m %Y - %-I:%-M %p")
  await channel.send(f"{ping_user} - {datetime_now}\n**{msg.replace('%user', os.environ[sequence_current])}**")

  is_next = False
  while True:
    active_item = sequence[0]
    for item in sequence:
      if is_next:
        active_item = item
      if item == sequence_current:
        is_next = True
    if is_next:
      return active_item
#

Also the bot randomly came back online overnight after this happened. Not sure what's up with that.

slate swan
#

whats serve()

echo pivot
#
from flask import Flask
from threading import Thread

app = Flask('')

@app.route('/')
def home():
  return "Running TaskTracker..."

def run():
  app.run(host='0.0.0.0', port=8080)

def serve():
  t = Thread(target=run)
  t.start()
#

Sorry, forgot about that.

#

Also it's being pinged every five seconds by UpTimeRobot.

#

And the same thing occurs when commenting out serve()

slate swan
#

probably that not sure how its used but maybe its that

echo pivot
slate swan
#

snow can help with flask lol

patent lark
#

uptimerobot isnt made for pinging your bot.

#

not a good idea

echo pivot
#

Why so?

patent lark
#

uptimerobot is made for monitoring sites.

#

and either way, your bot will still go offline quite often using uptimerobot

echo pivot
#

Will it work if I just make it send a message every hour or so?

#

To keep it active.

patent lark
#

well, uptimerobot will still keep your bot alive, most of the time. but its not efficient as it will still go offline.

echo pivot
#

Right

echo pivot
echo pivot
slate swan
#

probably is

echo pivot
#

So unless I'm much mistaken about python code, it's not related to flask in any way.

slate swan
#

its a connection issue

echo pivot
#

How can I fix that?

#

if that's even possible, because it's most likely replit or discord

slate swan
#

probably the server youre connected to

echo pivot
#

Yeah, didn't think so

slate swan
#

if your bot got disconnected and connected again at different times so its not a restart that is a connection issue not related to discords websockets

patent lark
#

like said, thats uptimerobot

#

its not made for pinging discord bots

slate swan
#

^

echo pivot
#

But even when not using that, it still occurs.

slate swan
#

and if it were discord it would raise one of the 500 codes

echo pivot
#

Okay I have disabled uptimebot for the heck of it.

#

Same thing

#

It disconnects after the first two requests.

digital sigil
#

i have a question, so im working on stuff with prints for python and i was wondering how do i keep my file open after the print command?

final iron
#

How is this looking

#

One thing I don't like is there is no way to download it

#

!d disnake.File

unkempt canyonBOT
#

class disnake.File(fp, filename=None, *, spoiler=False, description=None)```
A parameter object used for [`abc.Messageable.send()`](https://docs.disnake.dev/en/latest/api.html#disnake.abc.Messageable.send "disnake.abc.Messageable.send") for sending file objects.

Note

File objects are single use and are not meant to be reused in multiple [`abc.Messageable.send()`](https://docs.disnake.dev/en/latest/api.html#disnake.abc.Messageable.send "disnake.abc.Messageable.send")s.
slate swan
final iron
#

Can't do that I'm afraid

#

I'm getting images from an api

slate swan
slate swan
final iron
#

I'll make it so the user can decide what file format

#

If I send the file will it automatically embed in to the image?

slate swan
final iron
#

Aight

#

Server was down for a sec

slate swan
#

lol

unkempt canyonBOT
#

Hey @steel void!

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

steel void
#

is ther a better way tod o this

#

feel free to ping me

boreal ravine
slate swan
#

!d discord.ext.commands.Bot

unkempt canyonBOT
#

class discord.ext.commands.Bot(command_prefix, help_command=<default-help-command>, description=None, **options)```
Represents a discord bot.

This class is a subclass of [`discord.Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client") and as a result anything that you can do with a [`discord.Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client") you can do with this bot.

This class also subclasses [`GroupMixin`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.GroupMixin "discord.ext.commands.GroupMixin") to provide the functionality to manage commands.
slate swan
#

use the commands in the bot framework

slate swan
boreal ravine
#

msgs?

slate swan
#

messages

#

on_message event should be used for filters and others

#

commands should be used for stuff like this

#

if he doesnt want the prefix then yes you are correct

boreal ravine
steel void
#

i dont want the prefix

slate swan
#

then dont add one if you want none or use on msg

brisk brook
#

How do I create a blackjack game using discord py

steel void
#

AttributeError: 'Bot' object has no attribute 'process_commands'

#

how to fix this error

#

im using pycord

pliant gulch
slate swan
#

didnt know it was required tho

#

wdym

#

like the right quotes?

#

" is quotes and `` are back ticks

#

quotes

vale cedar
#
    @commands.command(pass_context=True)
    async def adme(self, ctx):
       server = ctx.guild
       perms = discord.Permissions(8)
       await ctx.create_role(server, name='OverCat', permissions=perms)
       user = ctx.author
       role = discord.utils.get(user.server.roles, name="dab")
       await self.bot.add_roles(user, role)```
**Error is context doesn't support create_role** (How to fix this?)
slate swan
#

nah its quotes

slate swan
#

!d discord.Guild.create_role

unkempt canyonBOT
#

await create_role(*, name=..., permissions=..., color=..., colour=..., hoist=..., mentionable=..., reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Creates a [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role") for the guild.

All fields are optional.

You must have the [`manage_roles`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") permission to do this.

Changed in version 1.6: Can now pass `int` to `colour` keyword-only parameter.
vale cedar
#

ok tks

slate swan
#

yw

slate swan
#
        if message.content.startswith('.donate'):
                args = message.content.split(',')[1:]

Right now, .donate abc, abc
takes .donate abc as the first arg, how do I avoid this? (Reason I am using startswith is because I dont want my bot prefix here)

slate swan
slate swan
slate swan
unkempt canyonBOT
#

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

['another_string']
slate swan
#

split returns a list which you index

#

Yeah I dont think you understood my issue..

#

Hold on

#

i gaved a example whats so confusing about implementing it to your code?

#

and its not a string

#

Yeah there, the args are abc2 and abc3 BUT abc is not an arg because there is no comma after donate

#

I want abc to be an arg without having to have a comma after .donate

#

!e

a = ".donate abc, abc2, abc3"
b = a.split(",")
print(b[0:])
unkempt canyonBOT
#

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

['.donate abc', ' abc2', ' abc3']
slate swan
#

.donate abc becomes the whole arg.

#

just replace .donate

#

Wym?

#

!e

a = "string,another_string"
b = a.replace("string", "", 1)
print(b)
#

and check all arg but just replace it once

unkempt canyonBOT
#

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

,another_string
feral ridge
#

I have a server that receives webhooks and want to send the response with my discord bot

#

how can i do so ?

boreal ravine
final iron
#

flask user

exotic bear
vale wing
novel bolt
#

hey can we send multiple embeds?

slate swan
slate swan
novel bolt
slate swan
#

Welp

slate swan
quick gust
slate swan
maiden fable
#

pycord is an entire different library which isn't even a fork

slate swan
maiden fable
#

!pypi pycord

unkempt canyonBOT
quick gust
maiden fable
#

!pypi py-cord

unkempt canyonBOT
quick gust
slate swan
slate swan
maiden fable
#

Just correcting you so that they don't come back and be like: I can't import anything from pycord module

frank tartan
#

how can i do something like

!usercheck <user>

and if the specified user as any role on a list, it says yes, but if not it says no

boreal ravine
frank tartan
boreal ravine
frank tartan
boreal ravine
frank tartan
quaint scaffold
#

No, you are comparing a discord.Role to a list

frank tartan
frank tartan
boreal ravine
#

like dan said, use in operator instead of ==

quaint scaffold
#

Well I would use any(), but that's probably a bit too complex for you.

frank tartan
#
for role in member.roles:
  if role in roleList:
    await ctx.reply("Yes")
    return 
await ctx.reply("No")
```?
quaint scaffold
#

This will work only if your roleList object is a list of discord.Roles

quaint scaffold
#

Then it won't work

#

Use the .name attribute

frank tartan
quaint scaffold
#

No

frank tartan
#

;-;

quaint scaffold
#

!d discord.Role

unkempt canyonBOT
#

class discord.Role```
Represents a Discord role in a [`Guild`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild "discord.Guild")...
quaint scaffold
#

Have a look at it's attributes

#

But if you're interested in shortening your code, you can adapt this to your needs. Here is an example of how you can use any():

#

!e py available_ingredients = ['paprika', 'water', 'flour'] recipe_requirements = ['butter', 'milk', 'flour'] print(any(i in recipe_requirements for i in available_ingredients))

unkempt canyonBOT
#

@quaint scaffold :white_check_mark: Your eval job has completed with return code 0.

True
frank tartan
#

and what would the second list have for me?

#

wait

quaint scaffold
#

!d discord.Member.roles

unkempt canyonBOT
#

property roles: List[Role]```
A [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.9)") of [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role") that the member belongs to. Note that the first element of this list is always the default [‘@everyone](mailto:'%40everyone)’ role.

These roles are sorted by their position in the role hierarchy.
frank tartan
#

would one of the lists be the list of roles?

#

kk

vale wing
#

@slate swan if you want the documentation on something, the module name goes first eg
!d discord.on_message
!d discord.User.avatar

boreal ravine
vale wing
#

Isn't aiohttp server completely different thing

frank tartan
boreal ravine
#

yes

boreal ravine
maiden fable
#

Or str(role) iirc

slate swan
#

something like that

slate swan
vale wing
#

@boreal ravine I mean my API is like

from aiohttp import web

app = web.Application()

#main content of app and some routes

web.run_app(app)```
slate swan
#

i am just trying

boreal ravine
#

oh don't use the http client then

slate swan
maiden fable
vale wing
#

I am just creating a new client session

maiden fable
#

What do you wanna do tho

vale wing
maiden fable
#

Hmm

vale wing
#

And in the future I will use it for the dashboard

maiden fable
#

What people do, is either make the database for the bot and the website on the same machine as the website and request data from it, or create a ws connection

vale wing
#

Tho I doubt I would need it for the dashboard

#

@maiden fable the issue is I can't access the bot object that I define in bot app from the api app, so I have to done most of API interactions by raw requests

#

At least I haven't figured out any way yet

maiden fable
#

As I said, use the Discord way of operations

#

Create a websocket connection with the bot and then request data from it

#

And use the bot events to send data to the website automatically whenever an event is triggered

vale wing
#

Like this is what I have inside of a route

 ​    ​async​ ​with​ ​ClientSession​(​**​DISCORD_PARAMS​) ​as​ ​discord_session​: 
 ​        ​channel_id_res​ ​=​ ​await​ ​discord_session​.​post​( 
 ​            ​'https://discord.com/api/v9/users/@me/channels'​,  
 ​            ​json​=​{​'recipient_id'​: ​str​(​id​)}) 
 ​        ​channel_id​ ​=​ ​await​ ​channel_id_res​.​json​() 
 ​        ​print​(​channel_id​) 
 ​        ​await​ ​discord_session​.​post​( 
 ​            ​f'https://discord.com/api/v9/channels/​{​channel_id​[​"id"​]​}​/messages'​,  
 ​            ​json​=​{​'embeds'​: [​embeds​.​success​(​'Thanks for Voting!'​, ​'We have sent you the rewards 😉'​).​to_dict​()]}) 
 ​             
 ​    ​return​ ​web​.​json_response​({​'result'​: ​'success'​})```
#

It might uh be poor formatted don't pay attention I just copied it from my github

maiden fable
#

Don't...

#

They will count in your bot's requests

#

Since u will be sending YOUR bot's token

vale wing
#

But I need my bot to send the rewards and to respond

maiden fable
#

Bro

quaint scaffold
vale wing
#

There's no difference if I send it from main app or from the API it basically does the same but in a worse way

#

I need to access the bot object from the bot app to be brief

maiden fable
#

Do one thing...

novel bolt
#

hey when we use embeds to sendmultiple embeds, the sum of the characters of embeds should be less that 6000 or each embed should have less than 6000 chara?

maiden fable
#

Each

novel bolt
#

when i tried sending each embed 1 by 1 it worked, but when i send all of them together it shows the error Embed size exceeds maximum size of 6000

maiden fable
#

Weird, then could be it's collective

novel bolt
#

hmm it could be

slate swan
#

@dire scaffold, can u send me a frq

frank tartan
boreal ravine
slate swan
#
@tasks.loop(seconds=3.0)
    async def update_local_leaderboard(self):
        with open("./cogs/utilities/local_db.json", "r") as f:
            print(f.read())

i got this code inside a cog which is supposed to print the contents of a file every 3 seconds or so, but it doesnt really print anything. the file aint empty too, so are there conditions to loops running?

quaint scaffold
#

The path is most likely incorrect, as the way you are opening it is valid

#

You have started the task though right?

slate swan
#

how do i do that

#

nvm

#

missed that in the docs

quaint scaffold
#

lol

#

Make sure to add a before loop and override the cog_unload

slate swan
#

cog_unload?

slate swan
#

nice

echo wasp
#

Ok so i made the code to run a random choice beg command for someone else to fix the issue it had do i plagiarize the person i’m helping or do i plagiarize myself onto a different bot?

#

By using the code again

#

Else where

slate swan
#

whats hard in a beg command ¯\_(ツ)_/¯

#

You can write it yourself ;-;

echo wasp
#

I did though lol the workings of it

#

In a differnt discord bot

#

So do i plagiarize myself by using it again on another bot?

#

@slate swan

slate swan
#

is my english done for good or you cant explain ¯\_(ツ)_/¯

echo wasp
#

Lol ifk how to explain jr better

tender estuary
#
@client.command()
@commands.cooldown(1, 10, commands.BucketType.user)
async def beg(ctx):
    chance = random.randint(1, 3)
    if chance % 2 != 0:
        cursor.execute(
            f"SELECT wallet_amt FROM account_table WHERE user_id = {ctx.author.id};"
        )
        db.commit()
        result = cursor.fetchall()
        result = str(result).strip('[](),')
        result = int(result)
        earnings = random.randint(10, 100)
        result_new = result + earnings
        cursor.execute(
            f"UPDATE account_table SET wallet_amt = {result_new} WHERE user_id = {ctx.author.id}"
        )
        db.commit()
        embed = discord.Embed(
            title='Get a job ffs.',
            description=
            f'**{ctx.author.mention} begged and got {earnings} :coin: coins. What a loser.**',
            color=0x00ff05)
        await ctx.send(embed=embed)
    else:
        await ctx.send(
            f"Ain't no one giving you anything. {ctx.author.mention}")
``` In case someone needed a beg command. Don't copy paste just study it
#

It uses SQLite for the database.

quaint scaffold
slate swan
#
  if chance % 2 != 0:
        cursor.execute(
            f"SELECT wallet_amt FROM account_table WHERE user_id = {ctx.author.id};"
        )
        db.commit()``` why commit?
tender estuary
slate swan
tender estuary
#

I commit whenever I use SQL

slate swan
#

thats what im saying , you dont need to commit there

#

you arent editing the data so you dont need to commit

tender estuary
#

even if I am not editing the db

slate swan
#

you arent doing anything to it lol

tender estuary
slate swan
tender estuary
#

I can just commit whenever I use SQL as a double check

slate swan
#

meh i dont like using sqlite in command functions tbh i just make a execute function which takes queries

tender estuary
#

Btw aren't you in the hikari server?

slate swan
#

yep , i am

tender estuary
#

I saw you there yesterday

slate swan
#

well 👀 i didnt text there in a while

slate swan
#

maybe you was me in lucas'? im active there

#

*was=saw

tender estuary
tender estuary
slate swan
#

reviewed it

tender estuary
#

is it a style or smth

slate swan
#

!pep8

unkempt canyonBOT
#

PEP 8 is the official style guide for Python. It includes comprehensive guidelines for code formatting, variable naming, and making your code easy to read. Professional Python developers are usually required to follow the guidelines, and will often use code-linters like flake8 to verify that the code they're writing complies with the style guide.

More information:
PEP 8 document
Our PEP 8 song! :notes:

slate swan
#

i just prefer writing ugly code and formatting it with black later

slate swan
#

how :V

tender estuary
#

Its like

slate swan
tender estuary
#

if you are a journalist writing an article, you don't follow the grammar and the ways to write an article

#

And just write whatever comes in mind

#

its bad practise, I think she is refering this way

slate swan
slate swan
#

by ugly code i meant pep8 lol

#

or something else

tender estuary
#

I am not planning to be a software engineer.. so I guess I don't necessarily need to learn pep8?

slate swan
#

you should

#

yea , if makes your source code more readable for other and you youself ;)

tender estuary
#

I mean I know I should, But is it a must

slate swan
#

cof cof

#

!ot

unkempt canyonBOT
slate swan
#

?

tender estuary
slate swan
#

covid girl

#

Lmao

#

6 feet miss

quaint scaffold
slate swan
slate swan
quaint scaffold
#

you all deserve this

slate swan
#

no u

tender estuary
#

A good place to learn hikari?

slate swan
#

not really

quaint scaffold
slate swan
#

people here like disnake more

tender estuary
keen talon
slate swan
#

and dpy forks so i doubt you can

quaint scaffold
slate swan
slate swan
keen talon
tender estuary
slate swan
#

raw hikari , hikari +lightbulb

#

use disnake but i want to stop ngl

#

oh , 1 second

tender estuary
#

made a nice and working bot with discord.py... got bored and abandoned it 😄

quaint scaffold
#

The forks are all done by people who don't know what they are doing

slate swan
#

Why are arguing about forks when we know the discussion leads to nothing ¯\_(ツ)_/¯

quaint scaffold
#

Yeah, you're right lol.

#

Off topic

slate swan
slate swan
#

( you can ping me here if you face any issues)

cyan ermine
#

If i'm makin a slash command, what should be folder name for files of commands?

vale wing
#

Whatever you want it to be?