#discord-bots
1 messages · Page 937 of 1
I have declared it in global scope but when I try to append an url into it, the program breaks
yeah
Show me the error
i'd go for disnake
Do you need the code
better devs and 2.0 is long since stable
queue is a command
hm
pls dont use repl in my opinion
waww kayle has pfp now
yes 😄
Hm
niceee
like actually
replit isnt good as they use shared ips, just cause its free dont use it
Wow
But replit is the only cloud hosting service I know
Do you know other alternatives
replit is crap for hosting
it isn't good for discord bots lol
thas true
ur the one who said abt it lmfao
Indeed
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
try to ask in #databases
Aha for sure
bro idk who asked fr
hey how does bot.add_view() work in disnake?
go rant somewhere else
same as d.py 2.0 .-.
heroku/railway are just fine for small applications
i dont like wasting people's money
Adds a persistent view that picks up interactions after a bot restart
cool? 💀
wait, I don't have persistent view
Then don’t use add_view
then?
will it work after bot restarts?
no
then what is the solution?
How do add the skip feature for the bot, I have tried using queue.pop(0) and voice.stop()
pause. remove the video from queue. and play the next in line if there is one?
I think pause is stop playing the music until we use resume
And I use play to play a song on yt using it url
then pop it and play the next?
anyone can help me with a roleplay bot?
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
Use add_view
What are you using wave link for?
Trying to make a music bot
From YouTube?
No
Hm alright since that’s against tos and usually wavelink is used for that
Yeah I know that..
For your error though you don’t have to pass in client
But should it be bot=client?
That’s what the errors saying, it didn’t expect to get client= passed in
Missing Authorization header
Or not
Check the documentation for that
what's this
Your token was invalid
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
you haven't an if in that send statement
what do you want to do?
i created a few cogs for server/channel muting, but i made a few mistakes in the booleans
just gotta fix those
wait you want to get the @everyone role and check its permissions?
or overwrite them / change them?
yes, but not only that role
i added options for muting multiples roles
AND i FORGOT discord.PermissiomsOverwrite returns False, None, or True for any key
ohh
now im going to have to suffer the next 3 hours
readability?
?
One of the statements is None
@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
yeah, just found this out

Bye
Oh lol
!zen
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!
so i just have to add a few checks for explicit denial and im set
isnt it ctx.voice_client?
@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)
!d discord.ext.commands.Context.voice_client

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.
!d disnake.Member.voice
property voice```
Returns the member’s current voice state.
Also we're not allowed to help with music bots.
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)
This is not yt dl
read the TOS properly
or other YouTube video downloaders
cya
#bot-commands
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
it isnt removing the role
Thanks a ton
tho i'll have to manually put in the code id right
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
ic
24/7 ?
use uptime robot
it doesnt
outdated
its outdated doesnt work anymore
most of the search results here
afaik its not good at all
mb, but still why are you using idle and thats not even how you should import lib.
I edited the file but still showing error
uh
@slate swan its red
I recommend atom very light weight as well with proper highlighting.
did that as well
Ohhh
english uk ig
They banned replit from using their services
idk
Leave any questions in the comments!
We will be making our bot run 24/7 in this video, we also have to write one line of code to make discord commands to work!
KEEP_ALIVE WEBSITE CODE:
from flask import Flask
from threading import Thread
app = Flask('')
@app.route('/')
def home():
return "Hello. I am alive!"
def run():
app.run(host='...
keep alive isnt even for hosting
that tutorial is trash lmao
Lol
youre probably running 2 instances of your bot
does it work in win7?
sublime is lightweight aswell
res69 = ["Yes","no","Hohoho","eugh"]
@bot.event
async def on_message(message):
if message.channel.id == 958013053557940304:
await message.channel.send(random.choice(res69))
you need to return if the author is itself
how to fix
hm
@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
why not use asyncio.sleep(5)
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"
what
obvio not cause the program shouldnt sleep
......
like the message has the word
program doesnt sleep
no
oh wai
== is the right operator to compare, youre assigning
!paste
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.
im dumb ty
i meant this
np
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")
hm
i want the bot to say "randomnumber/10" when anyone says "rate my this" "rate this " "ben rate this"
oki
a command or an elif statement if on message
what
check if the content of the message starts with what you want
noooo i don't want it to just start with what i wannttt
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")```
is there a way to like have a word in the middle or at any part of the sentence
Don't spoonfeed
ik i made some mistaake here kayle but
im sry
yes
yes,
- make a paginator, integrate it with your help command
- use discord-ext-menus
- use a 3rd party library

hm
it no work
wait
are you doing it in the above mentioned channel
Yes
if i weren't then why it is responding in "hohoho" "yes"
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))
try now
im sry im not used to the time module and #python-discussion
is that related to discord bots?
was that supposed to be funny?
discord py related topics must come here
others #python-discussion
ah
ok
sry if it sounded harsh
just following rules
try it
i edited it try that too
Okay
can u send it, its not letting me copy it correctly
send it agai
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")
i think he's not in the mood
lmfao
bro is this a ben bot?
wait im dumb
lol
do u love god?
still...
What is happening
channel.reply
is happening
and it freaks me out
await message.channel.reply(random.choice(numb6r) + "/10")
!d discord.Message.reply
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`.
i want it to happen in only one channl
it's just message.reply(f"{random.choice(numb6r)}/10")
it's still only gonna respond to that message...
the message object is bound to that channel
either message.reply or message.channel.send
message.reply(f"{random.choice(numb6r)}/10")
it's what I'm doing

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
👆
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?
why is rate even there
alo y two 5s
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
Won't work xd
does bot.has_permissions() apply to the user who invoked command or to the bot itself
the user
ty
tell me why ain't nothing but a hard way
yeah that's not what he wants
atleast not the number part
ping
meme numbers
he has 1-10, 69, 100, -1000
1 - 10, 69, 100 and -1000
and you would want if "rate" in message.content.lower()
Hey so
Nvm sorry it will, except for being case sensitive and a long way
yeah
bot.clear()
Cleares the State of the Bot = does mean that it gets "restarted"?
!d discord.ext.commands.Bot.clear
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.
along with the bot’s internal cache cleared.
is_ready doesn't launch switched with on_ready
so is there a way to restart the bot?
cogs ❤️
i mean most u can do is unload and load cogs
closing the script way to big of a hassle
and use os to run python bot.py
or Reloading sounds better, since it does the same
or closing the window, opening cmd, cd to the file, python bot.py all with os
overcomplication wooooooo
!d discord.ext.commands.Bot.reload_extension
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.
lemme guess new in 2.0
probably
nah
That has been since 1.6
it's 1.7
that's just the parameter that's 1.7 let's stop
nvm the names are the cogs
Setup supervisor and do os.system("reboot") 😀
No and won't ever do
alrighty
!d discord.ext.tasks.loop
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").
Use this instead, it's more efficient
please don't
can anyone help
1 sec
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
on_message event and simple if condition
im not sure if the bot.process_commands is needed
if message.lower() == "hello"```
Why put such condition lol
ay dont ask me
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")
So never give complete solutions
this is my code but
Nice : )
thank you master for teaching me your ways 🧎♂️
someone knows how to do this?
``json
{
"success":true,
"Amount":3,
"line":"lol:gir3
{
``
I wanna get certain element from json and print it
we literally sent it
Modals
do what?
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
lmao
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
OR ```py
@tasks.loop(minutes=1)
async def foo():
await bot.wait_until_ready()
pass
foo.start()```
Don't start a loop in on_ready.
i guess it would be a problem if he were to have loops in cogs

For different guilds?
Having loops in cogs is better
of course
Database
i dont doubt that, i told him that aswell
Guilds are Servers right?
It would be like
| id | welcome_channel_id |```
Those are the same things?
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
basically yeah in the context of after joining a server it would write a message in the welcome channel
apparently
Well, finding who created the channel is kinda complicated
You would have to iterate through audit logs and find the correct entry
on_guild_channel_create
on_private_channel_create
functions for that what you need
or just basically if they dont have the "administrator" permission they shouldnt be allowed
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
make a count
it might not work but try f.count(str(ctx.author))
i did and it didnt work. in short: it would read 7 lines or more from the author before it actually did anything
The "more than 5 lines" is a string or a list right?
its the file
its in the file
a file with multiple lines basically
every ctx.author is in a seperate line
hm
Ok got it
then how would i do an if statement, so if its over the count of 5
the str.count is an integer
it returns the number of how many times that element has been found in the string
id = str(ctx.author.id)
if any(id in line for line in f.readlines()):
...```
presuming it would be like
Totoro
juzzi
juzzi
Perhaps you meant this?
no
similar
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
im trying to make it an if statement. is that not possible with the code you provided?
Why can't you check if the content is in entire file
Why do you have to iterate through lines
you could do that with the count
It is
idk how, but theres one ctx.author per line anyway
Count is more expensive procedure than simple in
Idk what can be simplier than this
if str(ctx.author.id) in f.read():
...```
you really dont get it xD
Maybe
filelines = file
count = filelines.count(ctx.author)
if(count > 5):
do something
i think
i want to make an if statement like this, but in the correct words:
if str(ctx.author) in more than 5 lines:
count just returns how many times ctx.author was found in the filestirng
txt files welp
and based off of that you should be able to start something
this also got me confused, how can i implement it into this?
with open("/root/Textfiles/ongoing.txt", "r") as f:
lines = f.readlines()
More compact
if f.read().count(str(ctx.author.id)) > 5:
...```
there you go
You don't really have to read lines, just read the whole file
with open("/root/Textfiles/ongoing.txt", "r") as f:
if f.read().count(str(ctx.author.id)) > 5:
like this?
And uh if you want to speedup you can but the solution would be a bit more complicated
yeah .read = reads the whole file
.readline = reads one line at a time
Yeah
alright, let me try it out and i will update yall
kk
@vale wing you are my syntax translator for python xd
i dont know python all too much still transitioning
and readlines returns a list of lines
forgot to add that
Glad to help
and using txt files for storing data isnt a good option too though
i need ideas for a discord bot
its a good start for new people
you did tictactoe?
nah don't wanna do tictactoe tho
wait......what
not tictactoe 😳
i meant txt files
yeah
its not good
you recommend databases?
Chess bot cuz why not
You will have a lot of nice time trying to figure out engine communications
or json files for data that is less edited
json files are alright
uhh rather not
trickier than txts
i already have enough headaches
You want a light project right?
but not suitable to serve as databases
maybe one that is cool and unique but somewhat lighter
Random idea generator
lmao
I hardly think that unique is a thing now
Hamburger builder bot
lmao
xd
Why can i not use for loops in a discord command?
there is boring/bored api ig, thats the name iirc
you can
it wont work for me for some reason
code?
Depends what you are using it for
for
whenever i add a for loop in my command it just doesn't respond
send ur code
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
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
Hell
yeah its temporary
@slate swan Sometimes the easiest answer isnt always the best one
You don't iterate file
im going to use mysql when i actually use the bot
And that sfine
what
let that sink in...
what do you mean by this?
syntax isnt right
||SQL is easy if you know what you are doing||
Not sure what you are trying to do but that makes no sense
that famous if
it checks through every line in the file if it contains the users ID
You need to iterate file.readlines()
if i put it in a for loop i don't
And you are iterating file
the file isnt a string until you read it into a string
Actually, iterating over a file opened as 'r' mode is equivalent to iterating file.readlines()
Really?
yeah its a weird one
Well didn't know
the way im doing it is correct right?
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)
I'd probably still go for file.readlines() because its clearer what you're doing
its just not working on discord.py
The help about help commands is in pins, check them out
This
You are matching integer ID with string ID present in your file
That should error, nvm.
I just tried again and it still wont work
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
if this is correct what he said
you are just checking the first line in the file
still wont work ^^
discord.py is weird it wont even tell me whats wrong
readlines gives a list
becaues of the try: except:
it would've threwn me an error even if i didn't put it in a try statement
The conclusion is: don't make .txt databases
for test purposes its not bad.
im not going to make a whole sql db for testing purposes
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.
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
do i need to add each command manually to it ? or does it just make a list of commands that i have for me
It is automatic
i take that back
this should work i don't know why it is not
are you even getting into te function?
did you test that?
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?
good choice
Yes it works without the for loop
the message i wrote not the reacted message
The bot constructor
@slate swan does your code throw any errors
Nope
And do you have an error handler?
huh?
this proves what now?
No i do not i just fix errors for what the program throws
Ok
read what you said.
im wrong in my statement im braindead
I mean it should either throw an error or send a message in any way
i thought u mean that readline itself returns a list
Weird it doesn't respond at all
and im braindead enough to say that .read does
One question, how do you call this function
Is this meant to be a command or a function for operating with database
Cause it is not static and is missing self
what is wrong with me
i use different files for my commands.
every minute you change your bots presence to the current time
#help-corn someone help
You don't have selfs at all
Non static methods must have self as first attribute
what is that
don't need self if the object is not being constructed
async def addUserToDb(self, ctx, user: int, help="whatever idc"):
if ctx.author.id != ...
return
if not isinstance(user, int):
return await ctx.send("gib id")
#check length
for line in open(path).readlines():
if user in line: return await ctx.send("user in db")
```thats how you should have made it
you don't need self
you need to do a client.status_task.start() in the on_ready function so it would run
I can do the loops, but it just don't work
every for loop i've tried it just doesn't work if i use it
but you do get into the functionm
Is the program even getting to the loop? Because you just used strip on a list and it didn't error.
The conditions above it are probably why it's not getting there.
whoops try status_task.start()
I beg you to NOT do anything in the ON_READY event
Hes not using cogs
on_ready is apparently sent multiple times and changing status there can crash the bot
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
imagine making an API call, or starting a task loop in on_ready, smh
no
Now do the same but not in on_ready, put the .start before your bot.run(token)
it's preferred to do some_task.start() OUTSIDE of an event/command
it should work aswell then
Yeah my brain was stuck on on_ready because of cog issues
i didnt know loops could be started in the init and decided to just start them in on_ready
which i ofcourse changed
you can just do ```py
@tasks.loop(minutes=69)
async def task_name():
await bot.wait_until_ready()
pass
task_name.start()```
you could run a task before running your bot and you could add the wait_until_ready function at the top of the task
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')```
print(req.json()["line"])
Key error: line
I know this is wrong channel but Idfk what channel to do
wdym?
create a random channel
@client.event
async def on_raw_reaction(payload):
if payload.message_id == 958024371115548772:
guild = client.get_guild(payload.guild_id)
if str(payload.emoji) == '💼':
await guild.create_text_channel(name='test-channel')```
you forgot to get the guild obj
Alright boys here comes my issue
👀
but its still not opening a new channel
really?
!d discord.on_raw_reaction_add
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.
@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')```
\💼
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.
🙂
use the unicode version or it won't work
which line?
i think i have the bot.reload_extension wrong
await bot.reload_extension(f"cogs.{ext}")
i probably have the cog names wrong
print(req.json()["line"])
Key error: line
are you sure all those cogs were loaded @ startup?
still not opening the new channel
hmm, is your cogs folder in the same dir as your bot script
mhh they were added
if that helps xd
So i have to load cogs after adding them?
seems to me like that command is on his main file
yeah
so that shouldn't matter
its not a list
so maybe try r'./cogs/gif_cog'
because if cogs is a folder that might work
someone help me
but the syntax discord.py uses to load an extension from a folder is .
cogs is indeed not a folder i thought that had to be added
it already parses it for you
What's the problem?
here is the code but still not opening a new channel
@hybrid mural just send a screenshot of your file structure real quick
there's your problem
Does it register the new reactions?
you don't have a "cogs" folder
then basically .gif_cog
it isn't stored in a cogs folder
i have added reaction by myself
is what it should be right
put print('test') before message_id check and tell me if you see the test in console
this?
yep
me when someone doesn't actually use the debugger 
okay
xD
same error
How do I put cooldowns on commands
!d discord.ext.commands.cooldown
@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.
@commands.cooldown
well that looks simpler than I thought
is the payload function inside a Cog or a main file?
thanks a lot 
you're welcome
i havent made cog yet
maybe try to do if '💼' in str(payload.emoji):
that's how i use my on_raw_reaction funcs
it doesn't even print the test
So the listener doesn't even get executed
have you actually checked his intents yet?
is it in a cog or not?
Nope
it's the first thing to do when an event doesn't fire properly
@hasty stump show us where your defined client
@hasty stump
that's the event, show us where you defined client
can't be intents then
welp
🤔
did you put the event in a cog or class of any sort?
no there isnt any cog
no because he's not using Cog.listener
try this
bruv, the print doesn't even get executed
oh yeah
yes thats what i am saying
Do you have the on_raw_reaction_add defined somewhere else?
yes
reaction role?
maybe try to print all of the events that the bot has
merge them xd
if you're going to use @client.event you can only have 1 of that event, so merge
but one is reaction role other one is ticket system
You can use them both

i have @client.event for role remove and bot online too?
also for welcome msg too
well, let me word that better
okay sure
Just
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
i will create whole ticket system under that?
no that's not the only solution
you can have listeners outside of cogs...
?
!d discord.ext.commands.Bot.listen
@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...
You can, but ofc there are prettier ways
i thought you can only use them in cogs
i am new discord.py user so i tried once to setup cog but failed if u can assist me
wrong assumption
at least that's what a user here told me
..on their side

@hasty stump change your @client.event's to @client.listen('on_raw_reaction_add')
hmm, almonds taste sweet
and then change both async function names to something else
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 😭
jesus christ use f-strings
f strings
Hahahah
please
i died a little inside looking at that
Did the... comment?
hey guyds
wasssup
I don't get why its wrong 😦
imma need me some help
there but didnt created new channel
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
just use \n
"hello" +code \n + "hello" code \n
no
and f-strings
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
em.add_field(name=items, value=f'{len(Giveaway_Items[i]['Members'])} {Giveaway_Items[i]['Winners']}')

pep8 will remember this
@slate swan
who
stylistic guide to python code
asked
limits the maximum chara~
pep8.revenge()
well just go fuck yourself then i suppose
lmaooo
wrench help me
did you try my if statement?
if '💼' in str(payload.emoji):
yes i suppose
em.add_field(name=items, value=f"""
Enterants: {str(len(Giveaway_Items[i]['Members']))}
Winners: {+str(Giveaway_Items[i]['Winners'])}"""```
remove that space
worked
also from now on, please avoid code screenshots
okay
!code-blocks
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.
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']))}"""
em.set_footer(text="Minecadia Trading Giveaways | Inactive")
^
SyntaxError: invalid syntax
how can i place the new channel under a category ?
like it created at top
that error is being caused by something else
It isn't
can i sent it where i want?
!d discord.Guild.create_text_channel
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...
thing was never closed
yes but first you need to grab the object that represents the specific category
makes sense
then you pass it to the category arg in the create_text_channel function
Category.create_text_channel(name='thing')
Use the category kwarg, it's in the docs above
or do that 
!d discord.Guild.get_channel
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.
oh
yeah, you can get the Category with this
that's not a kwarg
do cogs have to have a setup function?
all cogs have to have a setup function
OH
isnt that the init
Why not?
i mean yes, init is a "setup function"
but what im talking about is
def setup(bot):
bot.add_cog(Extension(bot))```
Extension 'gif_cog' has no 'setup' function.
It is a kwarg for GuildChannel.edit
yes no prolem i have that
where should i add get_channel(channel_id, /)
send me a screenshot of the code
at the end, you get the category channel, and create the text channel with it
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")
create_text_channel
what? we're talking about category in guild.create_text_channel
Why isn't it a kwarg?
example
my point is still valid
a kwarg is used when you are unsure of the number of arguments to pass to a function
since you're creating only one text channel
chanel
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...
The category kwarg is there, endpoints are same
if '💼 ' in str(payload.emoji):
category = guild.get_channel(id=id)
category.create_text_channel(name='name')```
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?
Yes, that too
what is the error
no? more like *args and **kwargs
no. a kwarg is a keyword argument such as foo=10
Where did you get this from?
*args and **kwargs are used when you want to accept an arbitrary number of positional or key word arguments
more like to satisfy the argument with its name
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
@quaint epoch
the error says it lol
read the error
category is a string as you can see
and it needs a CategoryChannel obj
It doesnt Open the form because the selector is wrong
not a string
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
so i shouldnt use str at top ? near payload?
when you passed Category = 'Application' that was incorrect, it expected a CategoryChannel object, instead it got a string
so pass the category obj
!d discord.CategoryChannel
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.
!d discord.Guild.get_channel
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.
get the category channel with this @hasty stump
where will i add that get_channel(channel_id, /)
you can do it in the last if statement
just grab all the objects, and pass them in statements that require it
can you get me the code?
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')
category_channel = guild.get_channel() # pass in category channel id here
await guild.create_text_channel(name='channel_name', category=category_channel)```
You can get category objects with guild.get_channel?
yes
it is a channel
Hm they should've made it get_category imo for readability
you can fork the wrapper and make this the only change, if you want
What are the internals for get_channel?
you made a typo
Is it discord.utils.get?
idk
remove the last bracket
oh daym
i have lots of assignments to complete, cya
cya
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
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```
Do you know of a way to "restart" the bot (not terminating the connection itself)
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]`.
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.
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
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
thanks. found this and it really helped https://janakiev.com/blog/python-shell-commands/
new version yes
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
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?
i cant reload my cogs man wtf
Guys pls read my problem :(((
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'
discord really is messing with u there
more traceback
bro why do you even respond to me
that was hours ago im not sure what point youre trying to prove
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
only str has that attr
oh the load extension takes an str yes
so "gif_cog"
gif_cog is in the same dir as main so
should work
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.
what do you mean?
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
make the same embed but change the part that has to be changed
im not sure if loaded means loaded by "add_cog"
umm what would that look like?