#discord-bots

1 messages · Page 937 of 1

rocky hornet
#

instead of subclassing Context can i do this?

async def tick(self):
    await self.message.add_reaction("✅")

commands.Context.tick = tick
zinc phoenix
#

I have declared it in global scope but when I try to append an url into it, the program breaks

rocky hornet
#

i'd go for disnake

zinc phoenix
#

Do you need the code

rocky hornet
#

better devs and 2.0 is long since stable

boreal ravine
zinc phoenix
#

Wait

#

Let me change the comand name

boreal ravine
#

hm

gaunt ice
rocky hornet
#

makes me think why people ask others to read their errors

#

it says in plain english

gaunt ice
#

waww kayle has pfp now

boreal ravine
#

yes 😄

zinc phoenix
gaunt ice
gaunt ice
#

replit isnt good as they use shared ips, just cause its free dont use it

zinc phoenix
#

Wow

#

But replit is the only cloud hosting service I know

#

Do you know other alternatives

rocky hornet
#
Railway

Railway is an infrastructure platform where you can provision infrastructure, develop with that infrastructure locally, and then deploy to the cloud.

#

replit is crap for hosting

zinc phoenix
#

Hm

#

Thanks

boreal ravine
rocky hornet
#

free solutions wont be super good

#

but they work

gaunt ice
#

ur the one who said abt it lmfao

boreal ravine
#

Indeed

inner epoch
#

Hey guys I currently had to shift to mariadb from mysql due to server change now the old python script used to work well but now whenever two diff databases are called using the bot it shows error that "MySQL closed connection"

Example:
Bot at first runs a command for database A [this works fine]
Later it run for database B [here it throws error]

I read something abt cursor.close() I dont think thats needed bcs that will close the intial cursor

rocky hornet
#

yeah

#

cool?

inner epoch
rocky hornet
#

bro idk who asked fr

honest shoal
#

hey how does bot.add_view() work in disnake?

rocky hornet
#

go rant somewhere else

placid skiff
rocky hornet
#

heroku/railway are just fine for small applications

#

i dont like wasting people's money

sick birch
rocky hornet
#

cool? 💀

honest shoal
sick birch
#

Then don’t use add_view

honest shoal
#

then?

sick birch
#

Just send a view regularly

#

Pass in your view instance to the view= Kwarg in ctx.send

honest shoal
#

will it work after bot restarts?

boreal ravine
#

no

honest shoal
#

then what is the solution?

zinc phoenix
#

How do add the skip feature for the bot, I have tried using queue.pop(0) and voice.stop()

static beacon
zinc phoenix
#

And I use play to play a song on yt using it url

static beacon
zinc phoenix
#

Hm

#

I have tried adding it but its not working either

#

Heres the code

hasty bison
#

anyone can help me with a roleplay bot?

crimson compass
#

Traceback (most recent call last):
File "C:\Users\evelt\PycharmProjects\pythonProject1\pythonProject\Munhay\venv\lib\site-packages\discord\http.py", line 300, in static_login
data = await self.request(Route('GET', '/users/@me'))
File "C:\Users\evelt\PycharmProjects\pythonProject1\pythonProject\Munhay\venv\lib\site-packages\discord\http.py", line 254, in request
raise HTTPException(r, data)
discord.errors.HTTPException: 401 Unauthorized (error code: 0): 401: Unauthorized

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
File "C:\Users\evelt\AppData\Local\Temp\Temp1_08038ff427dfbcd53740a88b821113f5-dcf8b81eea1a98a9cfc0d9af7626ef1effed81db.zip\08038ff427dfbcd53740a88b821113f5-dcf8b81eea1a98a9cfc0d9af7626ef1effed81db\ticketbot.py", line 125, in <module>
client.run("TOKEN")
File "C:\Users\evelt\PycharmProjects\pythonProject1\pythonProject\Munhay\venv\lib\site-packages\discord\client.py", line 723, in run
return future.result()
File "C:\Users\evelt\PycharmProjects\pythonProject1\pythonProject\Munhay\venv\lib\site-packages\discord\client.py", line 702, in runner
await self.start(*args, **kwargs)
File "C:\Users\evelt\PycharmProjects\pythonProject1\pythonProject\Munhay\venv\lib\site-packages\discord\client.py", line 665, in start
await self.login(*args, bot=bot)
File "C:\Users\evelt\PycharmProjects\pythonProject1\pythonProject\Munhay\venv\lib\site-packages\discord\client.py", line 511, in login
await self.http.static_login(token.strip(), bot=bot)
File "C:\Users\evelt\PycharmProjects\pythonProject1\pythonProject\Munhay\venv\lib\site-packages\discord\http.py", line 304, in static_login
raise LoginFailure('Improper token has been passed.') from exc
discord.errors.LoginFailure: Improper token has been passed.
Exception ignored in: <function _ProactorBasePipeTransport.del at 0x000001BAF702B910>
Traceback (most recent call last):
File "C:\Users\evelt\AppData\Local\Programs\Python\Python310\lib\asyncio\proactor_events.py", line 116, in del
self.close()
File "C:\Users\evelt\AppData\Local\Programs\Python\Python310\lib\asyncio\proactor_events.py", line 108, in close
self._loop.call_soon(self._call_connection_lost, None)
File "C:\Users\evelt\AppData\Local\Programs\Python\Python310\lib\asyncio\base_events.py", line 750, in call_soon
self._check_closed()
File "C:\Users\evelt\AppData\Local\Programs\Python\Python310\lib\asyncio\base_events.py", line 515, in _check_closed
raise RuntimeError('Event loop is closed')
RuntimeError: Event loop is closed

tried to do a ticket system but full of errors

#

@brave vessel

junior verge
#

Should this be bot=client or client=bot

#

I use client

sick birch
sick birch
junior verge
sick birch
#

From YouTube?

junior verge
#

No

sick birch
#

Hm alright since that’s against tos and usually wavelink is used for that

junior verge
#

Yeah I know that..

sick birch
#

For your error though you don’t have to pass in client

junior verge
#

But should it be bot=client?

sick birch
#

That’s what the errors saying, it didn’t expect to get client= passed in

vale wing
#

Or not

sick birch
vale wing
#

Nvm that's lib

#

Bad token

crimson compass
quaint epoch
#

can someone please run this command in a channel of theirs and tell me if it prints True? py @bot.command() async def foo(ctx): role = ctx.guild.default_role await ctx.send(((ctx.channel.overwrites_for(role)).view_channel and (ctx.channel.overwrites_for(role)).send_messages and isinstance(ctx.channel, discord.TextChannel))) because this BOOLEAN returns None, not True or False(it should return True in my case)

#

idk why that's happening

placid skiff
#

you haven't an if in that send statement

quaint epoch
#

fuck im going to have to rework all of this

#

nvm

placid skiff
#

what do you want to do?

quaint epoch
#

just gotta fix those

verbal sentinel
#

or overwrite them / change them?

quaint epoch
#

i added options for muting multiples roles

#

AND i FORGOT discord.PermissiomsOverwrite returns False, None, or True for any key

verbal sentinel
#

ohh

quaint epoch
#

now im going to have to suffer the next 3 hours

quaint epoch
unkempt canyonBOT
#

@boreal ravine :white_check_mark: Your eval job has completed with return code 0.

001 | The Zen of Python, by Tim Peters
002 | 
003 | Beautiful is better than ugly.
004 | Explicit is better than implicit.
005 | Simple is better than complex.
006 | Complex is better than complicated.
007 | Flat is better than nested.
008 | Sparse is better than dense.
009 | Readability counts.
010 | Special cases aren't special enough to break the rules.
011 | Although practicality beats purity.
... (truncated - too many lines)

Full output: https://paste.pythondiscord.com/odamebobus.txt?noredirect

quaint epoch
quaint epoch
#

okay okay, i get it

#

but thanks

#

cya

boreal ravine
#

Bye

quaint epoch
#

!zen

unkempt canyonBOT
#
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than right now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

quaint epoch
#

so i just have to add a few checks for explicit denial and im set

junior verge
#

Any idea?

lament mesa
#

isnt it ctx.voice_client?

junior verge
#
@client.command()
async def play(ctx: commands.Context, *, search: wavelink.YouTubeTrack):
    if not ctx.voice_client:
        vc: wavelink.PLayer = await ctx.author.voice.channel.connect(cls=wavelink.Player)
    elif not ctx.author.voice_client:
        return await ctx.send("First join a voice channel")
    else:
        vc: wavelink.Player = ctx.voice_client

    vc.play(search)
lament mesa
#

!d discord.ext.commands.Context.voice_client

cloud dawn
unkempt canyonBOT
#

property voice_client```
A shortcut to [`Guild.voice_client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild.voice_client "discord.Guild.voice_client"), if applicable.
junior verge
#

ah

#

lemme see

quaint epoch
#

!d disnake.Member.voice

unkempt canyonBOT
cloud dawn
quaint epoch
#

returns None if member is not connected to a vc

#

!yt-dl

unkempt canyonBOT
#

Per Python Discord's Rule 5, we are unable to assist with questions related to youtube-dl, pytube, or other YouTube video downloaders, as their usage violates YouTube's Terms of Service.

For reference, this usage is covered by the following clauses in YouTube's TOS, as of 2021-03-17:

The following restrictions apply to your use of the Service. You are not allowed to:

1. access, reproduce, download, distribute, transmit, broadcast, display, sell, license, alter, modify or otherwise use any part of the Service or any Content except: (a) as specifically permitted by the Service;  (b) with prior written permission from YouTube and, if applicable, the respective rights holders; or (c) as permitted by applicable law;

3. access the Service using any automated means (such as robots, botnets or scrapers) except: (a) in the case of public search engines, in accordance with YouTube’s robots.txt file; (b) with YouTube’s prior written permission; or (c) as permitted by applicable law;

9. use the Service to view or listen to Content other than for personal, non-commercial use (for example, you may not publicly screen videos or stream music from the Service)
junior verge
#

This is not yt dl

quaint epoch
cloud dawn
#

or other YouTube video downloaders

junior verge
#

alright

#

my bad

quaint epoch
#

cya

boreal ravine
#

#bot-commands

tropic flame
#
async def on_message(message):
    guild = message.author.guild
    times_up = datetime.utcnow() + timedelta(seconds=5) 
    if message.content.startswith("&"): 
        AE = message.content.replace('&',"")
        role = discord.utils.get(guild.roles, name=AE) 
        if role is not None and datetime.utcnow() < times_up: 
            await message.channel.send(f"{role} is retained you have 5 secs of safetime now" )
    elif datetime.utcnow() > times_up:
         await message.author.remove_roles(role)
         await message.channel.send(f"{role}+ your role has been removed as you failed to verify")```
#

guys this is the code i wrote so basically i want it that when i do &test it should keep the test role for 5 seconds and after 5 seconds it should remove it if i haven't done &test within the 5 seconds and so on

#

can someone please help me

tropic flame
#

Thanks a ton

#

tho i'll have to manually put in the code id right

dusk drift
#

how to make the bot so that it sends messages when someone types something in a channel ,for example there is a channel named "ai" and you type "hello" in ai channel and the bot replies and sends random word from a list

tropic flame
#

ic

dusk drift
#

i want it to be on a certain chanmel

#

how to do dat

#

okay (:

#

ik thankk

tropic flame
#

24/7 ?

dusk drift
#

use uptime robot

tropic flame
#

it doesnt

#

outdated

#

its outdated doesnt work anymore

#

most of the search results here

slate swan
#

afaik its not good at all

stray carbon
#

why syntax error

#

oof

#

it says syntax error

#

wait

slate swan
stray carbon
#

I edited the file but still showing error

dusk drift
#

@slate swan its red

stray carbon
#

im using old pc and vcs lags so i use idle

#

3.8.6

cloud dawn
stray carbon
#

did that as well

dusk drift
#

Ohhh

stray carbon
#

english uk ig

slate swan
#

They banned replit from using their services

stray carbon
#

idk

slate swan
#

keep alive isnt even for hosting

#

that tutorial is trash lmao

dusk drift
#

@slate swan wtf

stray carbon
#

Lol

slate swan
stray carbon
slate swan
#

sublime is lightweight aswell

dusk drift
#
res69 = ["Yes","no","Hohoho","eugh"]
@bot.event
async def on_message(message):
 if message.channel.id == 958013053557940304:
    await message.channel.send(random.choice(res69))
slate swan
#

you need to return if the author is itself

dusk drift
#

how to fix

slate swan
#

and use a listener

#

so you wont need to process on_message events

boreal ravine
#

hm

tropic flame
#
@client.event
async def on_message(message):
    guild = message.author.guild
    times_up = datetime.utcnow() + timedelta(seconds=5) 
    if message.content.startswith("&"): 
        AE = message.content.replace('&',"")
        role = discord.utils.get(guild.roles, name=AE) 
        if role is not None and datetime.utcnow() < times_up: 
            await message.channel.send(f"{role} is retained you have 5 secs of safetime now" )
    elif datetime.utcnow() > times_up:
         await message.author.remove_roles(role)
         await message.channel.send(f"{role}+ your role has been removed as you failed to verify")```
#

guys this is the code i wrote so basically i want it that when i do &test it should keep the test role for 5 seconds and after 5 seconds it should remove it if i haven't done &test within the 5 seconds and so on
can someone please help me

gaunt ice
#

why not use asyncio.sleep(5)

dusk drift
#
if message.content = "hello"
    await message.channel.send("hi")

how to make it so that it replies when the message HAS something like "why" so the bot will reply "because"

tropic flame
#

bruh

tropic flame
#

obvio not cause the program shouldnt sleep

gaunt ice
#

......

dusk drift
gaunt ice
#

program doesnt sleep

gaunt ice
#

alr

dusk drift
#

ah

#

wrong screenshot

gaunt ice
#

lol

#
    await message.reply("hi")```
slate swan
#

no

gaunt ice
#

oh wai

slate swan
#

== is the right operator to compare, youre assigning

gaunt ice
#

👍

#

im blind

last moss
#

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

tropic flame
dusk drift
#

i meant this

gaunt ice
dusk drift
#

i want it to reply "10/10"

#
res69 = ["Yes","no","Hohoho","eugh","Yes","no"]
numb6r = [1,2,3,4,5,6,7,8,9,10,100,69,-1000,5]

@bot.event
async def on_message(message):
    if message.author.bot:
        return

    if message.channel.id == 958013053557940304:
        await message.channel.send(random.choice(res69))
    elif message.content == "rate":
        await message.channel.reply(random.choice(numb6r) + "/10")
gaunt ice
#

hm

dusk drift
#

i want the bot to say "randomnumber/10" when anyone says "rate my this" "rate this " "ben rate this"

gaunt ice
#

hmm

#

wait

#

gib 2 mins

dusk drift
#

oki

slate swan
dusk drift
#

what

boreal ravine
dusk drift
#

noooo i don't want it to just start with what i wannttt

gaunt ice
#
numb6r = [1,2,3,4,5,6,7,8,9,10,100,69,-1000,5]
rate = ['rate']
@bot.event
async def on_message(message):
    if message.author.bot:
        return

    if message.channel.id == 958013053557940304:
        await message.channel.send(random.choice(res69))
        if any(word in message.content for word in rate):
         await message.channel.reply(random.choice(numb6r) + "/10")```
dusk drift
#

is there a way to like have a word in the middle or at any part of the sentence

gaunt ice
#

ik i made some mistaake here kayle but

gaunt ice
gaunt ice
#

read docs

#

discord py

#

abt the buttons

boreal ravine
#

yes,

  • make a paginator, integrate it with your help command
  • use discord-ext-menus
  • use a 3rd party library
gaunt ice
#

yes

#

kayle i have a doubt

slate swan
gaunt ice
#

hm

dusk drift
#

it no work

gaunt ice
#

wait

gaunt ice
gaunt ice
#

bruh

#

wait

dusk drift
#

if i weren't then why it is responding in "hohoho" "yes"

gaunt ice
#

its cause u passed the if statement of the res69 first

dusk drift
# gaunt ice its cause u passed the if statement of the res69 first

will it work if i...

res69 = ["Yes","no","Hohoho","eugh","Yes","no"]
numb6r = [1,2,3,4,5,6,7,8,9,10,100,69,-1000,5]
rate = ['rate']
@bot.event
async def on_message(message):
    if message.author.bot:
        return

    if any(word in message.content for word in rate):
        await message.channel.reply(random.choice(numb6r) + "/10")
    elif message.channel.id == 958013053557940304:
        await message.channel.send(random.choice(res69))
gaunt ice
quaint epoch
#

is that related to discord bots?

gaunt ice
#

was that supposed to be funny?

#

discord py related topics must come here

#

ah

#

ok

#

sry if it sounded harsh

#

just following rules

gaunt ice
dusk drift
dusk drift
#

send it agai

gaunt ice
#

res69 = ["Yes","no","Hohoho","eugh","Yes","no"]
numb6r = [1,2,3,4,5,6,7,8,9,10,100,69,-1000,5]
rate = ['rate']
@bot.event
async def on_message(message):
if message.author.bot:
return

if message.channel.id == 958013053557940304:
    await message.channel.send(random.choice(res69))
    if any(word in message.content for word in rate):
     await message.channel.reply(random.choice(numb6r) + "/10")
dusk drift
#

i think he's not in the mood

gaunt ice
#

lmfao

gaunt ice
#

wait im dumb

gaunt ice
cedar aspen
#

do u love god?

dusk drift
velvet compass
#

What is happening

cold sonnet
#

channel.reply

#

is happening

#

and it freaks me out

#

await message.channel.reply(random.choice(numb6r) + "/10")

#

!d discord.Message.reply

unkempt canyonBOT
#

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

A shortcut method to [`abc.Messageable.send()`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send") to reply to the [`Message`](https://discordpy.readthedocs.io/en/master/api.html#discord.Message "discord.Message").

New in version 1.6.

Changed in version 2.0: This function will now raise [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "(in Python v3.10)") or [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError "(in Python v3.10)") instead of `InvalidArgument`.
dusk drift
cold sonnet
#

it's just message.reply(f"{random.choice(numb6r)}/10")

cold sonnet
#

the message object is bound to that channel

#

either message.reply or message.channel.send

dusk drift
#

message.reply(f"{random.choice(numb6r)}/10")

cold sonnet
#

sure

#

with await ofc

gaunt ice
#

meh

#

help him pls

cold sonnet
#

it's what I'm doing

gaunt ice
cold sonnet
#

BUT

#

how didn't you have an error 2022?

#

lemme guess else: pass error handler

dusk drift
cold sonnet
#

I also recommend word in message.content.lower() in your any()

#

oh how dumb can I yet be

#

your rate is out of your scope innit

#

MMXII do you have an error handler which could eat up your errors?

#

because the last two mistakes should've raised an error

#

both of them

#

why are all asking this

verbal sentinel
cold sonnet
#
res69 = ["Yes","no","Hohoho","eugh","Yes","no"]
numb6r = [1,2,3,4,5,6,7,8,9,10,100,69,-1000,5]
rate = ['rate']
@bot.event
async def on_message(message):
    if message.author.bot:
        return

    if message.channel.id == 958013053557940304:
        await message.channel.send(random.choice(res69))
        if any(word in message.content for word in rate):
         await message.reply(f"{random.choice(numb6r)}/10")

rate undefined?

cold sonnet
#

the list will probably get some words later

#

idk bro it's not my code

verbal sentinel
#

alo y two 5s

cold sonnet
#

could be

@bot.event
async def on_message(message):
    if message.author.bot:
        return

    if message.channel.id == 958013053557940304:
        await message.channel.send(random.choice(["Yes","no","Hohoho","eugh","Yes","no"]))
        if any(word in message.content for word in ["rate"]):
         await message.reply(f"{random.choice([1,2,3,4,5,6,7,8,9,10,100,69,-1000,5])}/10")
#

and listen instead of event

#

cuz it's better

slate swan
#

Won't work xd

hybrid mural
#

does bot.has_permissions() apply to the user who invoked command or to the bot itself

buoyant zodiac
#

the user

hybrid mural
#

ty

cold sonnet
#

yeah that's not what he wants

#

atleast not the number part

nimble plume
#

ping

verbal sentinel
#

meme numbers

cold sonnet
#

he has 1-10, 69, 100, -1000

verbal sentinel
#

1 - 10, 69, 100 and -1000

cold sonnet
#

and you would want if "rate" in message.content.lower()

hybrid mural
#

Hey so

slate swan
cold sonnet
#

yeah

hybrid mural
#

bot.clear()
Cleares the State of the Bot = does mean that it gets "restarted"?

cold sonnet
#

!d discord.ext.commands.Bot.clear

unkempt canyonBOT
#

clear()```
Clears the internal state of the bot.

After this, the bot can be considered “re-opened”, i.e. [`is_closed()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.is_closed "discord.ext.commands.Bot.is_closed") and [`is_ready()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.is_ready "discord.ext.commands.Bot.is_ready") both return `False` along with the bot’s internal cache cleared.
slate swan
#

I think it's related to bot's cache , tho I'm not sure

#

hm

cold sonnet
#

along with the bot’s internal cache cleared.

#

is_ready doesn't launch switched with on_ready

hybrid mural
#

so is there a way to restart the bot?

cold sonnet
#

cogs ❤️

verbal sentinel
cold sonnet
#

or close the script

#

and reopen it

hybrid mural
#

closing the script way to big of a hassle

verbal sentinel
hybrid mural
#

i'd lke it clean

#

Alright cogs unloading and loading

#

got it

slate swan
#

or Reloading sounds better, since it does the same

cold sonnet
#

there's no reload cogs

#

or... new stuff

verbal sentinel
#

overcomplication wooooooo

slate swan
#

!d discord.ext.commands.Bot.reload_extension

unkempt canyonBOT
#

await reload_extension(name, *, package=None)```
Atomically reloads an extension.

This replaces the extension with the same extension, only refreshed. This is equivalent to a [`unload_extension()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.unload_extension "discord.ext.commands.Bot.unload_extension") followed by a [`load_extension()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.load_extension "discord.ext.commands.Bot.load_extension") except done in an atomic way. That is, if an operation fails mid-reload then the bot will roll-back to the prior working state.
cold sonnet
#

lemme guess new in 2.0

hybrid mural
#

probably

cold sonnet
#

nah

slate swan
#

That has been since 1.6

cold sonnet
#

it's 1.7

hybrid mural
#

or not

#

i assume package are the cogs?

cold sonnet
#

that's just the parameter that's 1.7 let's stop

hybrid mural
#

nvm the names are the cogs

vale wing
hybrid mural
#

@vale wing you worked with heroku before?

#

Does that work on that platform?

vale wing
#

No and won't ever do

hybrid mural
#

alrighty

slate swan
#

!d discord.ext.tasks.loop

unkempt canyonBOT
#

discord.ext.tasks.loop(*, seconds=..., minutes=..., hours=..., time=..., count=None, reconnect=True)```
A decorator that schedules a task in the background for you with optional reconnect logic. The decorator returns a [`Loop`](https://discordpy.readthedocs.io/en/master/ext/tasks/index.html#discord.ext.tasks.Loop "discord.ext.tasks.Loop").
slate swan
#

Use this instead, it's more efficient

hybrid mural
#

aww cmon

#

reload_extensions only takes 1 extension?

cold sonnet
#

please don't

hybrid mural
#
import random

@bot.event
async def on_message(message):
    if message.lower() = "hello":
        rnd = random.randint(1, <how much words you have from that list>)
        await message.channel.send(list[rnd])
    await bot.process_commands(message)

i think

vale wing
hybrid mural
#

im not sure if the bot.process_commands is needed

vale wing
#

Why put such condition lol

hybrid mural
#

ay dont ask me

vale wing
#

And yeah random.choice exists

#

Also @bot.listen() is better

dusk drift
#
res69 = ["Yes","no","Hohoho","eugh","Yes","no"]
numb6r = [1,2,3,4,5,6,7,8,9,10,100,69,-1000,5]
rate = ['rate']
@bot.event
async def on_message(message):
    if message.author.bot:
        return

    if message.channel.id == 958013053557940304:
        await message.channel.send(random.choice(res69))
        if any(word in message.content for word in rate):
         await message.channel.reply(random.choice(numb6r) + "/10")
vale wing
#

So never give complete solutions

dusk drift
#

this is my code but

slate swan
hybrid mural
placid skiff
#

someone knows how to do this?

slate swan
#

``json

{
"success":true,
"Amount":3,
"line":"lol:gir3
{
``
I wanna get certain element from json and print it

vale wing
spring flax
vale wing
#

Implementable with disnake for sure

#

Check examples folder on their repo

hybrid mural
#

Btw is there a way to always get the id from the "welcome" channel?

#

the channel that sais "this guy joined!"

#

Theres such an easier way to do that with @tasks.loop

#

with the asyncio.sleep?

#

its not wrong although definitely not the best method to do it

#

with @tasks.loop you can loop a function with either seconds, minutes, hour

#

Check with a print if you get to the function

#

cause basically what i would do is

slow fog
hybrid mural
#

find a way to get these out of the loop while still accessable:

now = date.today()
  cst_time_zone = pytz.timezone('US/Central')
  now_cst = now.astimezone(cst_time_zone).strftime("%I:%M %p")

And then implement the loop itself

@tasks.loop(minutes=1) #this is the loop everything in there is gonna get looped
async def status_task():
    await client.change_presence(status=discord.Status.dnd, activity=discord.Activity(type=discord.ActivityType.watching, name=f"Time {now_cst}"))


@client.event
async def on_ready():
  client.status_task.start()
  print(f"Logged in as {client.user}")

My thought on your code

#

wait why do you need this:

now = date.today()
  cst_time_zone = pytz.timezone('US/Central')
  now_cst = now.astimezone(cst_time_zone).strftime("%I:%M %p")
#

ok i get it

#

this is basically how @tasks.loop works

#

recommendable would also be to make a cog and run it in the cog itself

#

Try implementing tasks.loop and then see if the status is getting edited

#

wait so basically what youre trying to do is edit your status every minute so that its showing the time right?

#

if thats what im saying is right all you literally have to do is :

@tasks.loop(minutes=1) #this is the loop everything in there is gonna get looped
async def status_task():
    now = date.today()
    cst_time_zone = pytz.timezone('US/Central')
    now_cst = now.astimezone(cst_time_zone).strftime("%I:%M %p")
    await client.change_presence(status=discord.Status.dnd, activity=discord.Activity(type=discord.ActivityType.watching, name=f"Time {now_cst}"))

My brain isnt functioning well today this should be right

#

Also 1 more thing that i think isnt right is the

now = date.today()

#

Im not a python programmer but it seems to me that this would only give you the Day of today correct me if im wrong ill look it up

#

i think what youre looking for is

#

Look into datetime a bit more and reassure yourself what you want is what you get

#

should be it if the date.today is right

#

alright then try it out

#

mb

#

you have to import this:

from discord.ext import tasks

#

dont forget to start the loop in on_ready

#

i see you havent written it above

#
@client.event
async def on_ready():
  client.status_task.start()
  print(f"Logged in as {client.user}")

the client.status_task.start()

#

you have to start the loop for it to work

quaint epoch
cloud dawn
#

Don't start a loop in on_ready.

hybrid mural
#

i guess it would be a problem if he were to have loops in cogs

quaint epoch
vale wing
hybrid mural
#

of course

vale wing
#

Database

hybrid mural
#

i dont doubt that, i told him that aswell

hybrid mural
vale wing
#

It would be like

| id | welcome_channel_id |```
vale wing
cosmic agate
#

guys i have a task, so i want to make a on_channel_create event, where if the channel is not created by the owner, it should be deleted

hybrid mural
#

basically yeah in the context of after joining a server it would write a message in the welcome channel

hybrid mural
vale wing
#

You would have to iterate through audit logs and find the correct entry

hybrid mural
hybrid mural
slate swan
#
with open("/root/Textfiles/ongoing.txt", "r") as f:     
    lines = f.readlines()
    if str(ctx.author) in more than 5 lines:

Does anyone know how this line should actually be:

if str(ctx.author) in more than 5 lines:
#

"in more than 5 lines" is obviously incorrect, but idk the correct words for it

hybrid mural
#

make a count

hybrid mural
slate swan
# hybrid mural make a count

i did and it didnt work. in short: it would read 7 lines or more from the author before it actually did anything

vale wing
hybrid mural
slate swan
#

its in the file

hybrid mural
#

a file with multiple lines basically

slate swan
#

every ctx.author is in a seperate line

cosmic agate
#

hm

vale wing
#

Ok got it

slate swan
hybrid mural
#

the str.count is an integer

#

it returns the number of how many times that element has been found in the string

vale wing
#
id = str(ctx.author.id)
if any(id in line for line in f.readlines()):
    ...```
hybrid mural
#

presuming it would be like

Totoro
juzzi
juzzi

vale wing
#

Perhaps you meant this?

slate swan
hybrid mural
#

Lets say this is the string

a = "12:13:14"

and i would do

a.count(':')

It would return 2 since the number of times the ':' has been found in the string is 2

slate swan
#

im trying to make it an if statement. is that not possible with the code you provided?

vale wing
#

Why can't you check if the content is in entire file

#

Why do you have to iterate through lines

hybrid mural
slate swan
#

idk how, but theres one ctx.author per line anyway

slate swan
#

cause i dont get it

vale wing
hybrid mural
#

its simpler aswell though

#

youre right ik but its one way i can think of

vale wing
#

Idk what can be simplier than this

if str(ctx.author.id) in f.read():
    ...```
vale wing
#

Maybe

hybrid mural
slate swan
#

i want to make an if statement like this, but in the correct words:

if str(ctx.author) in more than 5 lines:
vale wing
#

Oh wait got it now

#

Yeah the count is suitable for this case

#

Got confused by that in

hybrid mural
#

count just returns how many times ctx.author was found in the filestirng

slate swan
#

txt files welp

hybrid mural
#

and based off of that you should be able to start something

slate swan
vale wing
hybrid mural
#

there you go

vale wing
slate swan
#

like this?

vale wing
#

And uh if you want to speedup you can but the solution would be a bit more complicated

hybrid mural
#

yeah .read = reads the whole file
.readline = reads one line at a time

slate swan
#

alright, let me try it out and i will update yall

hybrid mural
#

kk

#

@vale wing you are my syntax translator for python xd

#

i dont know python all too much still transitioning

slate swan
hybrid mural
#

forgot to add that

slate swan
#

and using txt files for storing data isnt a good option too though

haughty quartz
#

i need ideas for a discord bot

hybrid mural
#

its a good start for new people

hybrid mural
haughty quartz
#

nah don't wanna do tictactoe tho

hybrid mural
#

helps understand the newer additions from discord.py 2.0

#

alright

slate swan
hybrid mural
#

not tictactoe 😳

slate swan
#

i meant txt files

hybrid mural
#

yeah

slate swan
#

its not good

hybrid mural
#

you recommend databases?

vale wing
#

You will have a lot of nice time trying to figure out engine communications

slate swan
hybrid mural
#

json files are alright

haughty quartz
hybrid mural
#

trickier than txts

haughty quartz
#

i already have enough headaches

vale wing
#

You want a light project right?

slate swan
haughty quartz
vale wing
#

Random idea generator

hybrid mural
#

lmao

slate swan
#

I hardly think that unique is a thing now

vale wing
#

Hamburger builder bot

haughty quartz
#

lmao

hybrid mural
#

xd

slate swan
#

Why can i not use for loops in a discord command?

slate swan
haughty quartz
slate swan
haughty quartz
#

code?

vale wing
#

for

slate swan
#

whenever i add a for loop in my command it just doesn't respond

haughty quartz
#

send ur code

slate swan
#
class UserAdd:
    async def addUserToDB(ctx, user, help="Add a user to the database."):
        if ctx.author.id == app().AuthDiscID:
            try:    user = int(user)
            except:
                await ctx.send(" Please provide a user ID.")
                return
            if len(str(app().AuthDiscID)) != len(str(user)):
                await ctx.send(" Please provide a user ID.")
                return
            for x in open("D:\\Gradient Bot\\src\\DB\\DB.txt", "r"):
                if user in x.strip("\n"):
                    await ctx.send(f" This user [{user}] is already added to the DB. ")
                    return
                else:   pass
            with open("D:\\Gradient Bot\\src\\DB\\DB.txt", "a+") as AddUser:    AddUser.write(f"{user}\n")
            await ctx.send(" Successfully added user [{s}] to DB. ".format(s=user))
            return
        else:
            await ctx.send(" You do not have permission to use this command. ")
            return
vale wing
#

Nice

#

You are iterating file

slate swan
#

DB.txt 😔

#

i added

            for x in open("D:\\Gradient Bot\\src\\DB\\DB.txt", "r"):
                if user in x.strip("\n"):
                    await ctx.send(f" This user [{user}] is already added to the DB. ")
                    return

and it wont work

vale wing
slate swan
hybrid mural
#

@slate swan Sometimes the easiest answer isnt always the best one

vale wing
slate swan
#

im going to use mysql when i actually use the bot

hybrid mural
#

And that sfine

hybrid mural
#

let that sink in...

slate swan
hybrid mural
slate swan
vale wing
#

Not sure what you are trying to do but that makes no sense

hybrid mural
slate swan
vale wing
#

You need to iterate file.readlines()

slate swan
vale wing
#

And you are iterating file

hybrid mural
vocal plover
vale wing
#

Really?

vocal plover
#

yeah its a weird one

vale wing
#

Well didn't know

slate swan
fathom garnet
#

is anyone able to help me on a discord bot? i've followed a tutorial on how to make a bot but i don't have a help command. (i'm new to coding so help is really appreciated)

vocal plover
#

I'd probably still go for file.readlines() because its clearer what you're doing

slate swan
vale wing
#

This

grim oar
slate swan
#
            with open("D:\\Gradient Bot\\src\\DB\\DB.txt", "r") as CheckDB:
                if  (str(user)) in CheckDB.readlines().strip("\n"):
                    await ctx.send(f" This user [{user}] is already added to the DB. ")
                    return
                else:   pass
#

or maybe the pass is causing the problem

hybrid mural
#

you are just checking the first line in the file

slate swan
#

discord.py is weird it wont even tell me whats wrong

grim oar
#

readlines gives a list

hybrid mural
hybrid mural
#

readlines = read a line

slate swan
#

it would've threwn me an error even if i didn't put it in a try statement

vale wing
#

The conclusion is: don't make .txt databases

slate swan
#

im not going to make a whole sql db for testing purposes

hybrid mural
#

f.read() reads the file as an individual string, and so allows relatively easy file-wide manipulations, such as a file-wide regex search or substitution.

f.readline() reads a single line of the file, allowing the user to parse a single line without necessarily reading the entire file.

vale wing
#

Well that would be better if you did. Once you are done with testing, you could transfer some code you made during the tests without additional migration

fathom garnet
# vale wing This

do i need to add each command manually to it ? or does it just make a list of commands that i have for me

vale wing
#

It is automatic

slate swan
hybrid mural
#

did you test that?

fathom garnet
# vale wing It is automatic

i've added it to my code but i don't know exactly how to make it fully work , is there anything im supposed to edit?

slate swan
slate swan
hybrid mural
slate swan
#

but i just want it to check if the ID is already in the txt file

vale wing
#

@slate swan does your code throw any errors

vale wing
#

And do you have an error handler?

hybrid mural
slate swan
#

No i do not i just fix errors for what the program throws

vale wing
#

Ok

grim oar
hybrid mural
#

im wrong in my statement im braindead

vale wing
#

I mean it should either throw an error or send a message in any way

hybrid mural
#

i thought u mean that readline itself returns a list

vale wing
#

Weird it doesn't respond at all

hybrid mural
vale wing
#

Is this meant to be a command or a function for operating with database

#

Cause it is not static and is missing self

hybrid mural
slate swan
hybrid mural
#

every minute you change your bots presence to the current time

south brook
slate swan
hybrid mural
#

do you get an error?

#

welp i see you still didnt run the task

vale wing
#

Non static methods must have self as first attribute

cold sonnet
#

what is that

grim oar
#

don't need self if the object is not being constructed

slate swan
slate swan
hybrid mural
#

you need to do a client.status_task.start() in the on_ready function so it would run

slate swan
#

every for loop i've tried it just doesn't work if i use it

hybrid mural
vale wing
#

Bruh that thing is complicated as heck

#

Just use cogs

grim oar
#

The conditions above it are probably why it's not getting there.

hybrid mural
#

whoops try status_task.start()

slate swan
hybrid mural
#

Hes not using cogs

grim oar
#

on_ready is apparently sent multiple times and changing status there can crash the bot

hybrid mural
#

oh yeah i see

#

then if its in main

#

just write it before the bot.run(token) and please dont show your token if you send the code

#

@slate swan

quaint epoch
hybrid mural
#

ay AY

#

everyone has their humble beginnings im still learning

hybrid mural
#

Now do the same but not in on_ready, put the .start before your bot.run(token)

quaint epoch
#

it's preferred to do some_task.start() OUTSIDE of an event/command

hybrid mural
#

it should work aswell then

hybrid mural
#

i didnt know loops could be started in the init and decided to just start them in on_ready

#

which i ofcourse changed

quaint epoch
#

you can just do ```py
@tasks.loop(minutes=69)
async def task_name():
await bot.wait_until_ready()
pass

task_name.start()```

slate swan
hasty stump
#

i want to create a channel when they react on my msg emoji

async def on_raw_reaction(payload):
    message_id = payload.message_id

    if message_id == 958024371115548772:
        guild = payload.guild_id
        if payload.emoji.name == '💼':
            await guild.create_text_channel('test-channel')```
slate swan
#

print(req.json()["line"])
Key error: line

slate swan
hasty stump
quaint epoch
#

you forgot to get the guild obj

hasty stump
#

oh wait what

#

i see

hybrid mural
#

Alright boys here comes my issue

quaint epoch
hasty stump
quaint epoch
hasty stump
grim oar
#

!d discord.on_raw_reaction_add

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.
quaint epoch
#
@client.event
async def on_raw_reaction_add(payload: discord.RawReactionActionEvent):
    if payload.message_id == 958024371115548772:
        guild = client.get_guild(payload.guild_id)
        if str(payload.emoji.name) == ':briefcase:':
            await guild.create_text_channel(name='test-channel')```
hybrid mural
#
extensions = ["gif_cog", "animals_cog", "tiktaktoe_cog", "music_cog", "help_cog"]

@bot.command(name="restart")
@commands.has_permissions(manage_roles=True, administrator=True)
async def restart(ctx):
    await ctx.send("Restarting...")
    bot.clear()
    for ext in extensions:
        await bot.reload_extension(f"cogs.{ext}")
    await ctx.send("Done!")

im getting error:

from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: ExtensionNotLoaded: Extension 'cogs.gif_cog' has not been loaded.

🙂

slate swan
#

use the unicode version or it won't work

hybrid mural
hybrid mural
#

i probably have the cog names wrong

slate swan
#

print(req.json()["line"])
Key error: line

#

are you sure all those cogs were loaded @ startup?

hasty stump
quaint epoch
hybrid mural
#

if that helps xd

hybrid mural
#

So i have to load cogs after adding them?

slate swan
slate swan
#

so that shouldn't matter

quaint epoch
#

because if cogs is a folder that might work

hasty stump
#

someone help me

slate swan
#

but the syntax discord.py uses to load an extension from a folder is .

hybrid mural
slate swan
#

it already parses it for you

tidal hawk
hasty stump
slate swan
#

@hybrid mural just send a screenshot of your file structure real quick

grim oar
#

readlines returns a list

slate swan
#

there's your problem

tidal hawk
slate swan
#

you don't have a "cogs" folder

hybrid mural
#

then basically .gif_cog

quaint epoch
hasty stump
hybrid mural
#

is what it should be right

slate swan
#

so you need to do reload_extension('{ext}')

#

just change that and try again

tidal hawk
tidal hawk
slate swan
hasty stump
hybrid mural
swift acorn
#

How do I put cooldowns on commands

hasty stump
#

no it dont

slate swan
unkempt canyonBOT
#

@discord.ext.commands.cooldown(rate, per, type=discord.ext.commands.BucketType.default)```
A decorator that adds a cooldown to a [`Command`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command")

A cooldown allows a command to only be used a specific amount of times in a specific time frame. These cooldowns can be based either on a per-guild, per-channel, per-user, per-role or global basis. Denoted by the third argument of `type` which must be of enum type [`BucketType`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.BucketType "discord.ext.commands.BucketType").

If a cooldown is triggered, then [`CommandOnCooldown`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CommandOnCooldown "discord.ext.commands.CommandOnCooldown") is triggered in [`on_command_error()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.discord.ext.commands.on_command_error "discord.discord.ext.commands.on_command_error") and the local error handler.

A command can only have a single cooldown.
quaint epoch
swift acorn
#

well that looks simpler than I thought

tidal hawk
swift acorn
#

thanks a lot CH_CheersHand

slate swan
hasty stump
#

i havent made cog yet

quaint epoch
#

maybe try to do if '💼' in str(payload.emoji):

#

that's how i use my on_raw_reaction funcs

tidal hawk
#

So the listener doesn't even get executed

slate swan
#

have you actually checked his intents yet?

quaint epoch
tidal hawk
#

Nope

slate swan
#

it's the first thing to do when an event doesn't fire properly

quaint epoch
#

@hasty stump show us where your defined client

tidal hawk
hasty stump
quaint epoch
slate swan
#

can't be intents then

quaint epoch
slate swan
#

🤔

quaint epoch
hasty stump
slate swan
quaint epoch
tidal hawk
quaint epoch
hasty stump
#

yes thats what i am saying

tidal hawk
#

Do you have the on_raw_reaction_add defined somewhere else?

hasty stump
#

yes

tidal hawk
#

Like do you have multiple of these

#

Well that's the problem

hasty stump
#

reaction role?

quaint epoch
#

maybe try to print all of the events that the bot has

hasty stump
quaint epoch
#

there's your problem

hasty stump
#

oh

#

how can i fix it then?

tidal hawk
#

merge them xd

quaint epoch
#

if you're going to use @client.event you can only have 1 of that event, so merge

hasty stump
#

but one is reaction role other one is ticket system

tidal hawk
#

You can use them both

quaint epoch
hasty stump
#

also for welcome msg too

quaint epoch
#

well, let me word that better

hasty stump
#

okay sure

tidal hawk
quaint epoch
#

if you want to have multiple of the same events, you'd have to use cogs, but since you are using @client.event you can't have multiple async functions of the same event, so the only solution is to merge

hasty stump
slate swan
#

you can have listeners outside of cogs...

quaint epoch
slate swan
#

!d discord.ext.commands.Bot.listen

unkempt canyonBOT
#

@listen(name=None)```
A decorator that registers another function as an external event listener. Basically this allows you to listen to multiple events from different places e.g. such as [`on_ready()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_ready "discord.on_ready")

The functions being listened to must be a [coroutine](https://docs.python.org/3/library/asyncio-task.html#coroutine "(in Python v3.10)").

Example...
tidal hawk
quaint epoch
hasty stump
slate swan
#

wrong assumption

quaint epoch
#

at least that's what a user here told me

slate swan
#

..on their side

quaint epoch
slate swan
#

@hasty stump change your @client.event's to @client.listen('on_raw_reaction_add')

quaint epoch
#

hmm, almonds taste sweet

slate swan
#

and then change both async function names to something else

kindred drum
#
em = discord.Embed(title="", color = discord.Color.gold())
                        em.add_field(name=items, value="""
                        Enterants: """+str(len(Giveaway_Items[i]['Members']))
                        """
                        Winners: """+str(Giveaway_Items[i]['Winners']))```
#
    ^
SyntaxError: invalid syntax```
#

how 😭

slate swan
#

jesus christ use f-strings

tidal hawk
#

Hahahah

quaint epoch
#

please

slate swan
#

i died a little inside looking at that

tidal hawk
#

Did the... comment?

hybrid mural
#

hey guyds

tidal hawk
#

wasssup

kindred drum
#

I don't get why its wrong 😦

hybrid mural
#

imma need me some help

hasty stump
quaint epoch
#

if you wana do something like py code_to_eval = '\n' + code that's fine, but if you're going to get data from multiple dicts and insert it in different parts of a string, f-strings are the way to go

cold sonnet
kindred drum
#

"hello" +code \n + "hello" code \n

quaint epoch
cold sonnet
#

and f-strings

slate swan
#
em = discord.Embed(title="", color = discord.Color.gold())
em.add_field(name=items, value=f"""
  Enterants: {str(len(Giveaway_Items[i]['Members']))}
  Winners: {str(Giveaway_Items[i]['Winners']))}"""```
#

that should work

tidal hawk
slate swan
hasty stump
cold sonnet
#

who

slate swan
#

stylistic guide to python code

cold sonnet
#

asked

slate swan
#

limits the maximum chara~

quaint epoch
#

pep8.revenge()

slate swan
#

well just go fuck yourself then i suppose

cold sonnet
#

lmaooo

hasty stump
#

wrench help me

slate swan
#

lets see, it didn't create the channel

#

you did change the function names, yes?

hasty stump
quaint epoch
hasty stump
quaint epoch
#

if '💼' in str(payload.emoji):

hasty stump
kindred drum
slate swan
hasty stump
#

worked

slate swan
#

also from now on, please avoid code screenshots

hasty stump
#

okay

slate swan
#

!code-blocks

unkempt canyonBOT
#

Here's how to format Python code on Discord:

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

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

kindred drum
hasty stump
#

like it created at top

slate swan
kindred drum
hasty stump
#

can i sent it where i want?

spring flax
#

!d discord.Guild.create_text_channel

unkempt canyonBOT
#

await create_text_channel(name, *, reason=None, category=None, position=..., topic=..., slowmode_delay=..., nsfw=..., overwrites=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

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

Note that you need the [`manage_channels`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_channels "discord.Permissions.manage_channels") permission to create the channel.

The `overwrites` parameter can be used to create a ‘secret’ channel upon creation. This parameter expects a [`dict`](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.10)") of overwrites with the target (either a [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") or a [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role")) as the key and a [`PermissionOverwrite`](https://discordpy.readthedocs.io/en/master/api.html#discord.PermissionOverwrite "discord.PermissionOverwrite") as the value.

Note

Creating a channel of a specified position will not update the position of other channels to follow suit. A follow-up call to [`edit()`](https://discordpy.readthedocs.io/en/master/api.html#discord.TextChannel.edit "discord.TextChannel.edit") will be required to update the position of the channel in the channel list...
kindred drum
slate swan
#

yes but first you need to grab the object that represents the specific category

kindred drum
#

makes sense

slate swan
#

then you pass it to the category arg in the create_text_channel function

quaint epoch
#

Category.create_text_channel(name='thing')

spring flax
slate swan
#

or do that CB_shrug

quaint epoch
#

!d discord.Guild.get_channel

unkempt canyonBOT
#

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

Note

This does *not* search for threads.

Changed in version 2.0: `channel_id` parameter is now positional-only.
hasty stump
#

oh

quaint epoch
slate swan
hybrid mural
#

do cogs have to have a setup function?

slate swan
hasty stump
#

OH

hybrid mural
spring flax
slate swan
#

i mean yes, init is a "setup function"

#

but what im talking about is

def setup(bot):
  bot.add_cog(Extension(bot))```
hybrid mural
slate swan
hasty stump
slate swan
quaint epoch
hybrid mural
# slate swan send me a screenshot of the code
class gif_cog(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        self.every_10_min.start()

    @commands.command(name="gif")
    async def gif(self,ctx, word):
        embed = discord.Embed(title="random GIF!", color=discord.Color.purple())
        session = aiohttp.ClientSession()
        if (word == "random" or word == "RANDOM" or word == " " or word == "" or word == None):
            response = "https://api.giphy.com/v1/gifs/random?api_key=j3zZt9Lx69BnInF2Y1178O8LzdloxwKl&tag=&rating=g"

        elif word == "cat":
            response = await session.get(
                "https://api.giphy.com/v1/gifs/random?api_key=j3zZt9Lx69BnInF2Y1178O8LzdloxwKl&tag=" + word + "&rating=g")
            data = json.loads(await response.text())
            embed.set_image(url=data['data']['images']['original']['url'])
            await session.close()

            await ctx.send(embed=embed)
            return
        else:
            response = await session.get(
                "https://api.giphy.com/v1/gifs/search?api_key=j3zZt9Lx69BnInF2Y1178O8LzdloxwKl&q=" + word + "&limit=&offset=0&rating=g&lang=en")
        data = json.loads(await response.text())
        gif_choice = random.randint(0, 200)
        embed.set_image(url=data[0]['data'][gif_choice]['images']['original']['url'])
        await session.close()
        await ctx.send(embed=embed)

    @tasks.loop(minutes=20)
    async def every_10_min(self):
        message_channel = self.bot.get_channel(950321866306908160)
        async with aiohttp.ClientSession() as session:
            request = await session.get('https://some-random-api.ml/img/cat')
            catjson = await request.json()
        embed = discord.Embed(title="Cat!", color=discord.Color.purple())
        embed.set_image(url=catjson['link'])
        await message_channel.send(embed=embed)
        await self.gif(message_channel, "cat")
spring flax
slate swan
spring flax
slate swan
slate swan
#

since you're creating only one text channel

hybrid mural
#

chanel

slate swan
#

and text channels can't be under two categories

#

!d discord.Guild.create_text_channel

unkempt canyonBOT
#

await create_text_channel(name, *, reason=None, category=None, position=..., topic=..., slowmode_delay=..., nsfw=..., overwrites=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

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

Note that you need the [`manage_channels`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_channels "discord.Permissions.manage_channels") permission to create the channel.

The `overwrites` parameter can be used to create a ‘secret’ channel upon creation. This parameter expects a [`dict`](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.10)") of overwrites with the target (either a [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") or a [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role")) as the key and a [`PermissionOverwrite`](https://discordpy.readthedocs.io/en/master/api.html#discord.PermissionOverwrite "discord.PermissionOverwrite") as the value.

Note

Creating a channel of a specified position will not update the position of other channels to follow suit. A follow-up call to [`edit()`](https://discordpy.readthedocs.io/en/master/api.html#discord.TextChannel.edit "discord.TextChannel.edit") will be required to update the position of the channel in the channel list...
slate swan
#

The category kwarg is there, endpoints are same

quaint epoch
# hasty stump example
if '💼 ' in str(payload.emoji):
  category = guild.get_channel(id=id)
  category.create_text_channel(name='name')```
uncut jacinth
#

Hey guys, Got a error on this one.

class accept_modal(ui.Modal, title = "Lets configurate your Server Profile"):
    answer = ui.TextInput(label = "Tell me the Name you Prefer", style= discord.TextStyle.short, placeholder = "Example: Distributor", required = False, max_length = 32 , min_length = 1)
    answer1 = ui.Select(options=[discord.SelectOption(label="1"), discord.SelectOption(label="2"),discord.SelectOption(label="3")])
    async def on_submit(self, interaction: discord.Interaction):

So basically i tried to do a select option it outputs a error someone know how to fix that?

slate swan
slate swan
slim ibex
slim ibex
#

*args and **kwargs are used when you want to accept an arbitrary number of positional or key word arguments

slate swan
#

more like to satisfy the argument with its name

uncut jacinth
# slim ibex what is the error
Traceback (most recent call last):
  File "C:\Users\lequi\Desktop\Qubic\discord.py\discord\app_commands\commands.py", line 531, in _invoke_with_namespace
    return await self._callback(interaction, **transformed_values)  # type: ignore
  File "C:\Users\lequi\Desktop\Qubic\discord.py\main.py", line 31, in accept
    await interaction.response.send_modal(accept_modal())
  File "C:\Users\lequi\Desktop\Qubic\discord.py\discord\interactions.py", line 789, in send_modal
    await adapter.create_interaction_response(
  File "C:\Users\lequi\Desktop\Qubic\discord.py\discord\webhook\async_.py", line 213, in request
    raise HTTPException(response, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In data.components.1.components.0: The specified component type is invalid in this context
hasty stump
#

@quaint epoch

quaint epoch
slate swan
quaint epoch
#

and it needs a CategoryChannel obj

uncut jacinth
quaint epoch
#

not a string

uncut jacinth
#

How could i fix that

#

answer1 = ui.Select(options=[discord.SelectOption(label="1"), discord.SelectOption(label="2"),discord.SelectOption(label="3")])#

#

I need a selection in the form body

#

but this code doesnt Work that ive made, So could you give me a Idea

hasty stump
quaint epoch
#

so pass the category obj

#

!d discord.CategoryChannel

unkempt canyonBOT
#

class discord.CategoryChannel```
Represents a Discord channel category.

These are useful to group channels to logical compartments.

x == y Checks if two channels are equal.

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

hash(x) Returns the category’s hash.

str(x) Returns the category’s name.
quaint epoch
#

!d discord.Guild.get_channel

unkempt canyonBOT
#

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

Note

This does *not* search for threads.

Changed in version 2.0: `channel_id` parameter is now positional-only.
quaint epoch
hasty stump
quaint epoch
#

just grab all the objects, and pass them in statements that require it

hasty stump
#

i am confused

#
@client.listen('on_raw_reaction_add')
async def on_raw_reaction_add(payload: discord.RawReactionActionEvent):
    print('test')
    if payload.message_id == 958024371115548772:
        guild = client.get_guild(payload.guild_id)
        if str(payload.emoji) in '💼':
            await guild.create_text_channel(name='test')
quaint epoch
# hasty stump can you get me the code?
category_channel = guild.get_channel() # pass in category channel id here
await guild.create_text_channel(name='channel_name', category=category_channel)```
spring flax
#

You can get category objects with guild.get_channel?

quaint epoch
#

it is a channel

spring flax
#

Hm they should've made it get_category imo for readability

quaint epoch
spring flax
#

What are the internals for get_channel?

quaint epoch
spring flax
#

Is it discord.utils.get?

quaint epoch
quaint epoch
hasty stump
#

oh daym

quaint epoch
#

i have lots of assignments to complete, cya

hybrid mural
#

AttributeError: module 'gif_cog' has no attribute 'setup'

#

y doe

#
async def setup(bot):
    bot.remove_command('help')
    await bot.add_cog(music_cog(bot))
    await bot.add_cog(tiktaktoe_cog(bot))
    await bot.add_cog(animals_cog(bot))
    await bot.add_cog(gif_cog(bot))
    await bot.add_cog(help_cog(bot))
    for ext in extensions:
        await bot.load_extension(ext)
#
extensions = ["gif_cog", "animals_cog", "tiktaktoe_cog", "music_cog", "help_cog"]

forgot to add this

south jetty
#
 try:
    await ctx.send(embed=embed, view=view)

 except UserNotFound:
     userfail = discord.Embed(title=f"{user.name} is not found.")
     await ctx.send(userfail=embed)```

```line 169, in wrapped
    ret = await coro(*args, **kwargs)
  line 21, in profile
    user = await roblox.get_user_by_username(username)
 line 131, in get_user_by_username
    raise UserDoesNotExistError
ro_py.utilities.errors.UserDoesNotExistError```
hybrid mural
#

Do you know of a way to "restart" the bot (not terminating the connection itself)

unkempt canyonBOT
#

os.execv(path, args)``````py

os.execve(path, args, env)``````py

os.execvp(file, args)```
These functions all execute a new program, replacing the current process; they do not return. On Unix, the new executable is loaded into the current process, and will have the same process id as the caller. Errors will be reported as [`OSError`](https://docs.python.org/3/library/exceptions.html#OSError "OSError") exceptions.

The current process is replaced immediately. Open file objects and descriptors are not flushed, so if there may be data buffered on these open files, you should flush them using `sys.stdout.flush()` or [`os.fsync()`](https://docs.python.org/3/library/os.html#os.fsync "os.fsync") before calling an [`exec*`](https://docs.python.org/3/library/os.html#os.execl "os.execl") function.
#

sys.executable```
A string giving the absolute path of the executable binary for the Python interpreter, on systems where this makes sense. If Python is unable to retrieve the real path to its executable, [`sys.executable`](https://docs.python.org/3/library/sys.html#sys.executable "sys.executable") will be an empty string or `None`.
#

sys.argv```
The list of command line arguments passed to a Python script. `argv[0]` is the script name (it is operating system dependent whether this is a full pathname or not). If the command was executed using the [`-c`](https://docs.python.org/3/using/cmdline.html#cmdoption-c) command line option to the interpreter, `argv[0]` is set to the string `'-c'`. If no script name was passed to the Python interpreter, `argv[0]` is the empty string.

To loop over the standard input, or the list of files given on the command line, see the [`fileinput`](https://docs.python.org/3/library/fileinput.html#module-fileinput "fileinput: Loop over standard input or a list of files.") module.

See also [`sys.orig_argv`](https://docs.python.org/3/library/sys.html#sys.orig_argv "sys.orig_argv").

Note

On Unix, command line arguments are passed by bytes from OS. Python decodes them with filesystem encoding and “surrogateescape” error handler. When you need original bytes, you can get it by `[os.fsencode(arg) for arg in sys.argv]`.
hybrid mural
#

Does this work on heroku?

#

i cant find anything else lol

unkempt canyonBOT
#

clear()```
Clears the internal state of the bot.

After this, the bot can be considered “re-opened”, i.e. [`is_closed()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.is_closed "discord.ext.commands.Bot.is_closed") and [`is_ready()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.is_ready "discord.ext.commands.Bot.is_ready") both return `False` along with the bot’s internal cache cleared.
hybrid mural
#

so cache gets cleared

#

then is_closed is false and is_ready is false

#

i could readd the cogs and then do clear

#

would be the most similar probably

slate swan
#

How can i see the output of
os.system("pgrep -f bot2.py")
This prints the PID of my second bot, but i don't know how to actually assign it to a variable

iron sorrel
#

new version yes

south jetty
#

?

#

I am confused

#

"If user failed, why are you doing user.name?" what do you mean

austere vale
#
async def giveaway(self, ctx, time, *, prize):
        
        giveawayembed = nextcord.Embed(
            title="🎉 New Giveaway! 🎉",
            color=0xfd9fa1
            )
        time=humanfriendly.parse_timespan(time)
        giveawayembed.add_field(name="Prize", value="{}".format(prize), inline=False)
        giveawayembed.add_field(name="Hosted by", value=f"{ctx.author.mention}", inline=False)
        giveawayembed.add_field(name="Ends in", value="{}".format(time))

        msg = await ctx.send(embed=giveawayembed)

how can i edit the "Ends in" embed so that it shows the time value that i put in? for example, if i put in 1m, it sets the embed to "Ends in 60" and just uses seconds only

cold sonnet
#

be a bit more consistent on those string usages

#

just a side comment

#

you have to remake the embed with a different third field

#

or...

#

embed.fields[2].name = "Not ends in" and then edit the message?

hybrid mural
#

i cant reload my cogs man wtf

minor panther
#

Guys pls read my problem :(((

hybrid mural
#
    await bot.reload_extension(gif_cog)

gif_cog.py is my cog and its in the same dir as the main.py and im getting this error:

AttributeError: type object 'gif_cog' has no attribute 'startswith'
cold sonnet
slate swan
#

that was hours ago im not sure what point youre trying to prove

hybrid mural
# cold sonnet more traceback
Traceback (most recent call last):
  File "C:\Users\leka\PycharmProjects\Amk\venv\lib\site-packages\discord\ext\commands\core.py", line 187, in wrapped
    ret = await coro(*args, **kwargs)
  File "C:\Users\leka\PycharmProjects\Amk\main.py", line 52, in restarts
    await bot.reload_extension(gif_cog)
  File "C:\Users\leka\PycharmProjects\Amk\venv\lib\site-packages\discord\ext\commands\bot.py", line 990, in reload_extension
    name = self._resolve_name(name, package)
  File "C:\Users\leka\PycharmProjects\Amk\venv\lib\site-packages\discord\ext\commands\bot.py", line 851, in _resolve_name
    return importlib.util.resolve_name(name, package)
  File "C:\Users\leka\AppData\Local\Programs\Python\Python310\lib\importlib\util.py", line 29, in resolve_name
    if not name.startswith('.'):
AttributeError: type object 'gif_cog' has no attribute 'startswith'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Users\leka\PycharmProjects\Amk\venv\lib\site-packages\discord\ext\commands\bot.py", line 1234, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\leka\PycharmProjects\Amk\venv\lib\site-packages\discord\ext\commands\core.py", line 923, in invoke
    await injected(*ctx.args, **ctx.kwargs)  # type: ignore
  File "C:\Users\leka\PycharmProjects\Amk\venv\lib\site-packages\discord\ext\commands\core.py", line 196, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: type object 'gif_cog' has no attribute 'startswith'

this is the full traceback

slate swan
#

only str has that attr

cold sonnet
#

oh the load extension takes an str yes

hybrid mural
#

so "gif_cog"

cold sonnet
#

it takes a path actually

#

yes

hybrid mural
#

gif_cog is in the same dir as main so

cold sonnet
#

should work

hybrid mural
#

then i get this: ```py
Traceback (most recent call last):
File "C:\Users\leka\PycharmProjects\Amk\venv\lib\site-packages\discord\ext\commands\core.py", line 187, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Users\leka\PycharmProjects\Amk\main.py", line 52, in restarts
await bot.reload_extension("gif_cog")
File "C:\Users\leka\PycharmProjects\Amk\venv\lib\site-packages\discord\ext\commands\bot.py", line 993, in reload_extension
raise errors.ExtensionNotLoaded(name)
discord.ext.commands.errors.ExtensionNotLoaded: Extension 'gif_cog' has not been loaded.

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
File "C:\Users\leka\PycharmProjects\Amk\venv\lib\site-packages\discord\ext\commands\bot.py", line 1234, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\leka\PycharmProjects\Amk\venv\lib\site-packages\discord\ext\commands\core.py", line 923, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
File "C:\Users\leka\PycharmProjects\Amk\venv\lib\site-packages\discord\ext\commands\core.py", line 196, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: ExtensionNotLoaded: Extension 'gif_cog' has not been loaded.

austere vale
slate swan
#

should be the same name as the file if its in a folder add the folder name if its in the same dir its just the name of the file

cold sonnet
hybrid mural
cold sonnet
#

hm

#

might be something in the file

austere vale