#discord-bots
1 messages · Page 1056 of 1
@tasks.loop(seconds=30)
async def checkforvideos():
with open("youtubedata.json", "r") as f:
data=json.load(f)
print("Now Checking!")
for youtube_channel in data:
print(f"Now Checking For {data[youtube_channel]['channel_name']}")
channel = f"https://www.youtube.com/channel/{youtube_channel}
html = requests.get(channel+"/videos").text
try:
latest_video_url = "https://www.youtube.com/watch?v=" + re.search('(?<="videoId":").*?(?=")', html).group()
except:
continue
if not str(data[youtube_channel]["latest_video_url"]) == latest_video_url:
data[str(youtube_channel)]['latest_video_url'] = latest_video_url
with open("youtubedata.json", "w") as f:
json.dump(data, f)
discord_channel_id = data[str(youtube_channel)]['notifying_discord_channel']
discord_channel_id = client.get_channel(int(discord_channel_id))
msg = f"<@&976169188274086019> {data[str(youtube_channel)]['channel_name']} Just Uploaded A Video Or He is Live Go Check It Out: {latest_video_url}"
await discord_channel_id.send(msg)
checkforvideos.start()
@checkforvideos.before_loop
async def checkforvideos():
print('waiting... 2 ')
await client.wait_until_ready()
@slash.slash(name="add_youtube_notification", description="admin only")
@commands.has_permissions(manage_roles=True)
async def add_youtube_notification(ctx, channel_id: str, *, channel_name: str):
with open("youtubedata.json", "r") as f:
data = json.load(f)
data[str(channel_id)]={}
data[str(channel_id)]["channel_name"]=channel_name
data[str(channel_id)]["latest_video_url"]="none"
#you can also get discord_channe id from the command
#but if the channel is same then you can also do directly
data[str(channel_id)]["notifying_discord_channel"]="975360118591991818"
with open("youtubedata.json", "w") as f:
json.dump(data, f)
await ctx.send("Added Your Account Data!") ```
!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.
!code
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.
man ;-; discord_slash
How can I convert this into tiktok instead of youtube
My friend has nokia but whose phone doesnt have backticks
sarcastic....?
iirc one of their phones did, maybe my bad
Prolly
Oh
while loading i get this error
Does it also include level system ye?
await client.load_extension
In discord 2.0 it's a coro
@slate swan yo indents fixed .
?
I fixed my indents lol
Ohhk nice
I still need help tho
your code's too messy 😭 you should try rewriting it without copying it
yes
Idk lol
Kk recommend it ig
Nokia doesn't have backticks
I'd rather be using discord superutils at this point even though the library sucks anyways
lol
oh
I have quite alot idk how to fix
Ok lemme show current code
Alr
For the event .
time stamps:
0:00 - intro
0:20 - discord bot setup
0:56 - online database setup
2:08 - project set up
3:40 - say hi to arc
3:50 - continue setup
4:56 - increasing XP
7:49 - rank command
9:55 - leaderboard
10:52 - adding cogs
11:05 - final product
11:15 - outro
———————
Thanks (for non copyright music):
----------------------------...
thats old
nooo
no rank card lol
just get the concept
Yt tutorials are trash
your code got errors above
never said to copy
you got a point
i meant using the mongo
😔
and basically level system is just an ap or gp formula however u want it
how do i make a warning system
copy that
above?
https://paste.pythondiscord.com/gohidaraji @slate swan here.
like....?
@warped mirage
above as in above the command
sure
!warn 925079016174682213
just store in a db
!warn {user}
and
warnings {user} which shows the warnings
and if sb has like 4 warnings he gets banned
yes it is in that command but how do i fix it
i do have v2.0
store in a db and if warncount == 4 then ban
yup
store the warnings in a db and check every time while getting warned
yes
I would suggest adding a boolean column that checks if the user is already banned or not
if not xp or not lvl
tf?
use sql or json anything
im out
idk how to use
Master's code..
don't touch json for that
whats that
Db
its fine for a small case warn system and a json here is not going to cause delays due to warn being rarely used and its only a one time use
Database
@slate swan best as i could
those langs to communicate with databases, their sole purpose is to store large amounts of data
ah
Structured query language derivations to help you with your database management
cant fit all in
enough for beginners
they are not databases uhhhhhhhhhh
they create a database
add cog is a coro
they interact with a database
details...
what

if not xp or level:
What do u want me to do
await bot.add_cog . . .
``` ?
Change it
client in your case
Ok
dont name commands.Bot to client 
Imma go and play some cHess I'm out
it must be async also
async def ....
god damn
Btw what’s said will that fix my code
Ye
because it wasn't async ig
What's the error
yup
No errors
Just doesn’t respond to the level command
And event is fucked I think
How do u know
What do u expect u didn't send anything 🤨
I sent a hastebin and a ss bruh
no like
I havbe the @tasks.loop() function
but I want to run it multiple times in parrarel
what do u mean by parrarel
Not for you
task.start()
task.start()
they running and doing they thing
🤨
its llike threads
🥶
U mean a loop start another loop ?
start the same loop twice. but w/ diff args
tasks.loop() with that use before and after loop
ping
oof
wut
u can use before and after loop which is function of the task.loop and run 3 diff functions if u want
for a in arg:
func(a)
im trynna do ```py
@tasks.loop(seconds=10)
async def balls(arg):
do stuff w args
@client.command()
async def uwu():
balls.start(arg1)
balls.start(arg2)
it doesnt let me do this
holyp
@slate swan can u check mine or nah
@tasks.loop(seconds=60) # task runs every 60 seconds
async def my_background_task(self):
#stuff
@my_background_task.before_loop
async def before_my_task(self):
await self.wait_until_ready()
mistake
👍
dont need to do that
you could add it directly to do the task
and it wont be a problem whenever it is looping
raise RuntimeError('Task is already launched and is not completed.')
RuntimeError: Task is already launched and is not completed.
Error says all
I imported it and I use buttons,select menu
Didn’t know all the changes in new version
he is trying to launch the same task twice
same task w/ diff args
is that even possible? idts
not before the first task is completed
im talking about a level system...
im trying to use discord tasks like how threads work
or define the parameters in the task and call the function in the task
but the ask here needs to in teract with the user
before loop will run it the first time then the main task loop will run it the second time
@warped mirage let me guess... the xp won't go above 3 and it says user leveled to same level every user message?
bot launch is going well, 30 servers in 5 days and 23 votes 
Its hard to describe whats going on but it is checking every line for the mentioned user, and then saying no if the line doesnt contain the user... I dont know if i said that right...
How could i fix that?
Wow cool
Which hosting btw?
Lucky
Nice
Mine is like 1.5 years or smth old, 155 servers and hardly any votes lol
Lol
No votes cz I don't really have anything locked behind a votewall lol
is bot validation cumbersome?
my other one had 800 servers in 6 months, so this is looking a lot better
Verification?
ur bot cmds are little complicated to use tbh
yep verification
Yes. U r full of anxiety when its submitted for verification. What if this happens, what if that happens, what if my bot switches off during verification, and so on
i think locking behind a votewall is fine for some things
I mean, it's a simple command, hunset #channel
Nice
get something for your work
Mine is just a chatbot, can't really lock anything
Can't find that 💀
Read the FAQs
Its full of buttons
I said hi
He said what do u like I started a different topic a replied and it send hmm interesting lol
that must be taking a ton of resources to host a chat bot no?
ANYONE KNOW HOW I CAN MAKE A TIKTOK NOTIFIER THERE IS NO TUTORIALS ONLINE ANYONE KNOW?
i would limit usage time per person per day and put that behind a vote wall
Disable caps
Caps
smart
that way only the people who are really enjoying your bot will run into the votewall
and theyll be happy to vote anyway most of the time
can someone recommend me a tut for level system
like PIL is blocking, and is there like any alternative to it or a way to make it run asynchronously?
like, running it using the event loop would be a good idea?
What are you using PIL for
stuff
creating images to be specific
Can anyone help me how to use @unkempt canyon in our bot pls
Me dont know how to use dockerfile
dockerfile isnt even related-
You can't use the python bot in your bot
@supple thorn 😔
do stuff in another thread?
i use pillow but haven't needed to make it run async
Hmm a guy told me about it
was thinking about it, maybe I'll do that, thanks
Btw do anyone know about how can we make a slot command and a database to it
slot command? what does it do?
what is a pokemon slot command
Dunno sorry
yeah, I just dropped the idea anyways, seemed useless lol
i think its like the slot machine u see in a casino
Ye
what specifically are you stuck on while making it
Hmm idk how to make
have you coded in python before?
Most likely a copied git
use bot.loop.run_in_executor
Can someone help me make a levelling system lol
quite helpful for this purpose
We provide help here relating coding issues, not make/ setup bots.
you didn't await load_extension
I still don't fully understand blocking and async code
would it block the function for everyone or just the person on that thread
!blocking
Why do we need asynchronous programming?
Imagine that you're coding a Discord bot and every time somebody uses a command, you need to get some information from a database. But there's a catch: the database servers are acting up today and take a whole 10 seconds to respond. If you do not use asynchronous methods, your whole bot will stop running until it gets a response from the database. How do you fix this? Asynchronous programming.
What is asynchronous programming?
An asynchronous program utilises the async and await keywords. An asynchronous program pauses what it's doing and does something else whilst it waits for some third-party service to complete whatever it's supposed to do. Any code within an async context manager or function marked with the await keyword indicates to Python, that whilst this operation is being completed, it can do something else. For example:
import discord
# Bunch of bot code
async def ping(ctx):
await ctx.send("Pong!")
What does the term "blocking" mean?
A blocking operation is wherever you do something without awaiting it. This tells Python that this step must be completed before it can do anything else. Common examples of blocking operations, as simple as they may seem, include: outputting text, adding two numbers and appending an item onto a list. Most common Python libraries have an asynchronous version available to use in asynchronous contexts.
async libraries
The standard async library - asyncio
Asynchronous web requests - aiohttp
Talking to PostgreSQL asynchronously - asyncpg
MongoDB interactions asynchronously - motor
Check out this list for even more!
would the entire bot stop processing anything until the pillow image is done though
yes
if it's within an async function
no
just for that thread right, the one person
you can make it run in executor to have it run asynchronously
it's not because you put sync code in an async function that it'll run asynchronously
If it's an async function the functions that you call inside that function are async.
your options are the following: find an async wrapper of the lib you're using / run in executor to have a sync function run async
so for argument sake
The best practice however would be to make your own async pillow api.
Ye
I'm quite busy today, just try to debug the commands one by one I'd say
Me learning from YouTube
async def on_message(message):
a_non_async_function()```
this would block anyone else receiving a response when sending a message until the first a_non_async_function is done
or just block each person until it's done
In general it blocks your entire bot
Particularly if it blocks heartbeats you’re going to get disconnected

Lol
yeah
Hmm do anyone know a tutorial on making a slot command?
It's like if you can't breathe and your heart can't beat at the same time xD
Most of those are custom.
Hmm like pokeslot command
there will not be tutorials for everything, u have to learn and make it yourself
i think when i tested my pillow image generation only takes 1/100th of a second or less
I’m terrible at python(
so shouldn't be a problem right
or when you drink a big bottle of water, you can't breathe until you finish
seeing as only 50 people can use the bot in a second for the discord api
If it's a small bot sure, but bigger bots have had issues with this.
Of python discord api
Hmm have had
XD good English
guys
???


huh? weren't there three discord-bots related threads??
what happened to the third one?
No clue
ImportError: cannot import name 'commands' from 'discord.ext' (unknown location) tf is happening
someone help me
Did you name a file/dir commands?
nope
Yea I got it
Didn’t know I had to await in 2.0
i downloaded nextcord , but then i deleted it
no
I recommend using pip list and see what is installed.
ok
you have to give us something for us to help you
we need code
Should I start making with random?
but i deleted it
start making it and then when you get stuck come and we will help
Thank u ☺️
ok good i fixed it
@dull terrace
Slot = random.randint(1,2,3,4,5)
Is it fine?
Will it work if i use it in command
Hmm how can I put more arguments?
Oh k
Means it will choose random from numbers between 1 and 5
yes, including 1 and 5
Ok
what are you trying to do?
@dull terrace
@client.command()
async def pokemonslot(ctx):
slot = random.randint(1,10)
if slot == 1:
await ctx.send("wow you won a uncommon charizard!")
This?
u need to take ctx as an arg for ur function
and u dont need to indent that if
Oh i forgot
indentations should be four spaces, you indent at the start of a function, the line after an if, for or while
I fixed in my code editor
How do I use on_message in cog?
My command worked

How can I save data in database?
Like how many Pokemon a user have won
SQLBolt provides a set of interactive lessons and exercises to help you learn SQL
good set of tutorials on databases
?
!d discord.ext.commands.Cog.listener
classmethod listener(name=...)```
A decorator that marks a function as a listener.
This is the cog equivalent of [`Bot.listen()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.listen "discord.ext.commands.Bot.listen").
But me never used database
Me not understanding about it
how can I add reactions to a message and start a thread just by message id rather than the obj? (using disnake)
How can we make that bot wait for 2 seconds and send message
unresponsive
oh wat
wait*
fixed it sorry for ping
Huh
how do i check if a message is having . . . in it?
not in start or end
can anyone help me with bot development on discord using python?
if '...' in message.content:
...
!d asyncio.sleep
coroutine asyncio.sleep(delay, result=None)```
Block for *delay* seconds.
If *result* is provided, it is returned to the caller when the coroutine completes.
`sleep()` always suspends the current task, allowing other tasks to run.
Setting the delay to 0 provides an optimized path to allow other tasks to run. This can be used by long-running functions to avoid blocking the event loop for the full duration of the function call.
Deprecated since version 3.8, removed in version 3.10: The `loop` parameter. This function has been implicitly getting the current running loop since 3.7. See [What’s New in 3.10’s Removed section](https://docs.python.org/3/whatsnew/3.10.html#whatsnew310-removed) for more information.
Example of coroutine displaying the current date every second for 5 seconds:
thanks! well, i need to know the framework required and a step by step process :) just need some guidance from someone experienced... i need to make it as a project...
The docs -> https://discordpy.readthedocs.io/en/stable/ (version 1.7.3)
https://discordpy.readthedocs.io/en/master/ (version 2.0)
The github examples -> https://github.com/Rapptz/discord.py/tree/master/examples
A basic bot example -> https://git.io/dpy-basic-bot
the tutorial doesnt show 1.7.3?
it shows a tutorial with nextcord and disnake
how to flatten in d.py v2.0?
wait what
click the tutorial lol
nvm
and that link is a redirect
i know its tutorial.vco...
should use the actual link as vco said it wasnt going to be a redirect for too long
i know 😔
🥰
any doc or help?
Flatten what?
flatten users in a reaction
It’s already a list isn’t it?
Oh just checked the docs
You can call .flatten() on it like usual
What does flatten do
It converts an AsyncIterator to a regular list
Oh
whats your issue?
just write it here
wheres your assets/css destination?
looks like you dont habve one
you dont have the folders assets and css
you gotta create an assets folder and in that folder a css folder and in the css folder a styles.css
how do I use dpy and change my bot's description using its token
after creating the list possible to mention em all?
thanks! i'll look into it :)
@slate swan wrong channel
claim a help channel
Don't ask for help to topics that are not in the channel's description
you dont flatten in 2.0 ```py
before
users = await reaction.users().flatten()
after
users = [user async for user in reaction.users()]
the iteration below #after does the same thing as flatten in 2.0
how can i make the mins arg multiply by 60 so it can be in int
for that, mins need to be an integer/float so typehint to int
guys can someone help me fix my levelling system
what issue do you face ?
mins is probably a string
you probably didn't type hint/convert it
well the command doesnt work and the event is messed up i think idk , can i show my code on a hastebin?
why doesn't this deposit function work
@client.command()
@commands.cooldown(1,5,commands.BucketType.user)
async def deposit(ctx, amount):
memberData = loadmemberdata(ctx.author.id)
if memberData.wallet < amount:
errorembed = discord.Embed(
title="LOL POOR BOZO",
description=f"DUDE YOU CANT DEPOSIT {amount} WHEN YOU ONLY HAVE {memberData.wallet}"
)
await ctx.channel.send(embed=errorembed)
else:
memberData.wallet -= amount
memberData.bank += amount
mbed = discord.Embed(
title="Monkebux deposited..",
description=f"You deposited {amount} monkebux into the bank"
)
await ctx.channel.send(embed=mbed)
no errors, just thaat the wallet and bank dont get affected at all
and the bot sends nothing
because you dont change anything!
Did you save it though?
¯_(ツ)_/¯
what's memberData
import pickle
class Data():
def __init__(self, wallet, bank):
self.wallet = wallet
self.bank = bank
client = commands.Bot(command_prefix = "-monkey ")
datafilename = "data.pickle"
def loaddata():
if os.path.isfile(datafilename):
with open(datafilename, "rb") as file:
return pickle.load(file)
else:
return dict()
def loadmemberdata(memberID):
data = loaddata()
if memberID not in data:
return Data(0,0)
return data[memberID]
def savememberdata(memberId, memberdata):
data = loaddata()
data[memberId] = memberdata
with open(datafilename, "wb") as file:
pickle.dump(data, file)
@client.command()
@commands.cooldown(1,5,commands.BucketType.user)
async def deposit(ctx, amount):
memberData = loadmemberdata(ctx.author.id)
if memberData.wallet < amount:
errorembed = discord.Embed(
title="LOL POOR BOZO",
description=f"DUDE YOU CANT DEPOSIT {amount} WHEN YOU ONLY HAVE {memberData.wallet}"
)
await ctx.channel.send(embed=errorembed)
else:
memberData.wallet -= amount
memberData.bank += amount
mbed = discord.Embed(
title="Monkebux deposited..",
description=f"You deposited {amount} monkebux into the bank"
)
await ctx.channel.send(embed=mbed)
savememberdata(ctx.author.id, memberData)
also i did import
discord and stuff
Does @lament depot have ludo or something related to dice 🤨
im surprised how are you using an int as a pickle dictionary key.
yeah im kinda new to pickle
well, using an actual database is a better option.
idk how to do that
can someone help me fix my leveling system or give me a code
How can I mention the users in list?
instead of doing user async for do user.mention async for
users = [user.mention async for user in reaction.users()]
await asyncio.sleep(mins)
await ctx.send(users.mention, delete_after=0.5)
nonetype has no attribute users
got this error ^
reaction is None
I have a reaction
On the embed I sent
you cant mention a list comp anyways....
And a variable for await add_reaction(. . .)
I mean
The users in the list are mentionable
If yes then how?
the list already contains the mention strings.....you just need to join the list into a single string....
Yup
Probably a list comp or map
can you show your full code
guys i need help
With?
my level system command is not working , and for the event it does this
and does that every message i do
Do we have any discord server for C too?
you need to indent your code properly, after level += 1
also, i think you want xp += random.randint(1, 3) instead of xp = random.randint(1, 3)
I created a basic welcome bot for a friend's server, which sends an Embed to new members, but I'm seeing inconsistent results. It always sends a message, but I'm using member.mention and that mention can be any of the following:
- Username (this is what I want)
- Userid (not desirable, it's just a long number)
- invalid-user (this one only seems to show up on my phone, but also undesirable)
import os
import discord
from discord.ext import commands
from dotenv import load_dotenv
load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')
intents = discord.Intents.default()
intents.members = True
bot = commands.Bot(command_prefix = '!', intents=intents)
@bot.event
async def on_member_join(member):
general_channel = None
guild_joined = member.guild
general_channel = discord.utils.get(guild_joined.channels, name='general')
if general_channel:
embed=discord.Embed(title="Welcome!",description=f"Welcome {member.mention}!!")
await general_channel.send(embed=embed)
bot.run(TOKEN)
Is something wrong in my code? Am I running into some sort of caching issue where the username isn't available yet? Just curious if anyone has any thoughts as to what might be causing the inconsistent behavior?
There isn't an error. It "sends" just displays the mention incorrectly. I thought I needed to use mention in order to actually "mention" them? Meaning doing an @ at them instead of just printing the text of their name?
so replace:
embed=discord.Embed(title="Welcome!",description=f"Welcome {member.mention}!!")
with
embed=discord.Embed(title="Welcome!",description=f"Welcome <@{member.id}>!!")
yes try that
ok. Thanks! I'll give it a try!
bot = commands.Bot(command_prefix="$")
uhh tahts the first time ive had that error
yeah idk what its talking about.
turn on the message intent and pass it into ur code
the intent is enabled in the portal what is the code that i need ot insert?
can u help me with this"?
Hey can someone tell me what is the issue here
eru jsk py
import aiohttp
import disnake
from io import BytesIO
query = "janji+heroes+tonight+ncs"
url = f'https://some-cool-api.herokuapp.com//youtube_music?query={query}'
async with aiohttp.request("GET", url=url) as response:
data = BytesIO(await response.read())
with open(f"./song.mp3", "wb") as f:
f.write(data.getbuffer())
channel = _bot.get_channel(919885560863146008)
await channel.send(file = disnake.File("./song.mp3"))```
Regarding point 3, we actually had this issue with someone else earlier. I don't know how exactly they fixed it, or even if it was fixed, but it's a software bug and there's nothing we can do about it
- happens when your client hasn't cached that user, not a bug but a limitation. Nothing you can do about that either
Unfortunately, in your case, you have 2 options:
- Leave it as is, and deal with the inconsistent mentions
- Change it to something plaintext that will always work, like the user's name and discrim
oh! ok, I hadn't tried the suggestion above in production yet. Sounds like there's no real need to? As in all/both cases, it's a software or cache limitation
Doesn't do anything: https://github.com/Rapptz/discord.py/blob/master/discord/member.py#L567-L570
discord/member.py lines 567 to 570
@property
def mention(self) -> str:
""":class:`str`: Returns a string that allows you to mention the member."""
return f'<@{self._user.id}>'```
Anyone pls?
That's correct. Nothing much you can do about it, except trying to put it in plaintext like I mentioned
Gotcha. That's great to know! Especially as a beginner with discord.py knowing it's not something I'M doing wrong
Thanks again @sick birch !
Yeah, it can be difficult to tell. Discord in general has a few quirks like this littered around.
Anytime
Doesn't seem directly related to a discord bot. You'd have better luck asking in #media-processing
Uh as you say..
But the code works fine when run
This happens only when running from jsk
@bot.command()
async def fetchall(ctx):
guild = ctx.guild
memberList = guild.members
for member in list(ctx.guild.members):
print(member)```
prints one member only which is the bot, why?
Traceback (most recent call last):
File "C:\Users\Harckepy\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "C:\Users\Harckepy\Desktop\shitty bot or smth\main.py", line 22, in on_message
role = discord.utils.get(message.guild.roles, "Awaiting on first message")
TypeError: get() takes 1 positional argument but 2 were given
``` this some bs
@bot.event
async def on_message(message):
role = discord.utils.get(message.guild.roles, "Awaiting on first message")
if(role in message.author.roles):
message.author.remove_roles(role)
await bot.process_commands(message)
do you know what utils.get does?
it returns the first element of a list that matches the given attribute value
why javascript?
yes
you don't have member intents
well, so you have a role named "awaiting on first message"? lol
in that case, all you forgot is the kwarg name=
oh i forgot to add these in this bot
i tried it with that earlier and had the sama error
since your role is very specific and probably not meant for multiple guilds, I suggest you to get it by ID
!d discord.Guild.get_role
get_role(role_id, /)```
Returns a role with the given ID.
Changed in version 2.0: `role_id` parameter is now positional-only.
how do people even get such insane ideas any ways. ..
idk 💀
stackoverflow/yt tutorials mb
still...
how the answers on stackoverflow are so top-notch smh
Look into subclassing HelpCommand
If you do not understand what exactly I am writing, do not even try to say anything, do not provoke me to insults.
how can I make it so that only the mentioned user can click on the button ?
async def interaction_check(self, interaction) -> bool:
if interaction.user.mention == False:
await interaction.response.send_message("Вы не можете ответить за друго-го участника", ephemeral= True)
return False
else:
return True```
mmm russian language
You have to figure out how to get the mentioned user into your view subclass
The most common way is to pass it in as an argument
what ?
Well, I did about the same nonsense
I don 't understand then what does he need from me ?
You need to compare the user who sent the interaction (e.g clicked the button) to the user who was mentioned. We can get the person who clicked the button using interaction.user, which you already seem to have. You just need to get the mentioned user in, by passing it in as arguments like I mentioned
This is not the way to ask for help. I know that you've been warned about your aggressive behavior before, so please take that to heart.
dude don't link me just like that
link you?
For example:
class MyView(discord.ui.View):
def __init__(self, member: discord.Member, ...):
super().__init__(...) # instantiate a view like usual
self.member = member
async def interaction_check(self, interaction: discord.Interaction):
return self.member == interaction.user # You can do anything else here, since you have access to the `member` object
@bot.command()
async def my_command(ctx: commands.Context, ...):
member: discord.Member = ... # this will be the only person who can click the button
view = MyView(member)
await ctx.send(view=view)
don't respond to my messages if you don't want to say something on the topic
hrmm my file structure is
Folder:whiskeybot
bot.py
.env
⇾cogs
⇾⇾events.py
how can i refence the .env inside the events cog?
I couldn't do it in def init(self, member: discord.Member, ...): put member: discord.Member
!mute 419481276765175808 1d You need to take some time to stop and think about what I and other moderators have told you. You cannot engage with our community like this.
:incoming_envelope: :ok_hand: applied mute to @brave forge until <t:1653244935:f> (23 hours and 59 minutes).
Wouldn't you be using something like dotenv to load it?
i am using dotenv
You could pass it to your cog from within setup()
will it call the .env that is a folder above?
usually you only want to access your .env once, when your bot is initially starting
from there you can pass your data around
Are you using extensions?
ell im also storing test guild ids there for slash commands and i need to ref them from there
yes
You can bind the data to a bot instance
Awaiting this object: <bound method Bot.hidden_commands of <bot.bot.Bot object at 0x10ec42b90>> would probably not give me any result, I assume.
Will it?
Then in setup, you can do like so:
class MyCog(commands.Cog):
def __init__(self, bot: commands.Bot, ...):
self.bot = bot
@bot.command()
async def some_command(self, ctx: commands.Bot, ...):
guild_ids = self.bot.data
# do something
def setup(bot: commands.Bot):
bot.add_cog(MyCog(bot=bot))
2.0 makes setup async, but same concept
The important bit is that you bind your .env data as a bot var
Btw, here:
Bot is a subclass of discord.ext.commands.Bot
and hidden_commands is an async function defined.
would that work through disnake?
What does the async function return?
nothing
Not sure, but just make sure you understand the concept
Ah, a void function?
async def hidden_commands(self):
"""
Hides the commands which require `role_checks` check.
`redirect_output` and `channel_checks` are exceptions.
"""
commands_ = [command_ for command_ in self.commands if 'role_check' in
[parent_check.__qualname__ for parent_check in command_.checks]]
for cmd in commands_:
print(cmd)
cmd.hidden = False
Then it should return None
print(cmd) was for debugging but it don't even do that when I run the bot
Are you actually awaiting it?
it's not even an async function
Pretty sure, I am.
for func in bot_.helper_functions:
print(func)
await func()
ah, there it is
Well, technically speaking it is, but I'm guessing you mean it has no need to be one?
right
bot_.helper_functions is just a list of functions such as [self.a, self.b]
Try printing something at the top of your hidden_commands function:
async def hidden_commands(self):
print("called")
...
yep. It's called
That is true. Since i don't have to await cmd.hidden = True
If that's called, my only other guess is that commands_ is empty
Also side note, but you should prefix your variable names with an _, not put it at the end, like _commands, but often times there's no need to even do that
I guess so.
If you're making a minecraft bot, python may not be the best language
can someone help me fix my leveling system
What's the issue?
Minecraft is written in Java, not Javascript. If you want to make minecraft bots, you should learn Java. Not to mention minecraft bots may be in violation Mojang's TOS, depending on how it's used
Yes please
ye its for any game tbf
what is the minecraft bot gonna do
discord is a website, and has its own API, minecraft does not have anything like that
its just an java app running on ur device
Exactly like so 
Discord is both a website and a desktop app, the latter of which uses Electron
robin do u know what possibly could be breaking my bot with the level system
wait how do i bind the data
It's going to be difficult to create a minecraft bot without knowing java
self.var_name = ...
If you're not subclassing: bot.var_name = ...
welp that didnt reply lol
ummm i dont understand what you mean lol
@warped mirage sorry, I'm having a difficult time reading the code. Do you get any errors? That may help me figure out what's wrong
Are you subclassing bot?
lemme start bot rq one sec
in the cog?
No, in general, are you subclassing bot?
It does this per message and for the command no response or error
You have any error handlers?
Nah
In that case I'm willing to bet this is a logic issue
What handler?
Error
No, it can harm you if you're not careful
Sometimes people make a global error handler and it eats up all errors
Tf
Yeah, that's why it's important to be careful with global error handlers
I’m so confused lmao
um i dont know what you mean but this it the code in my bot.py
import disnake
from disnake.ext import commands
import datetime
import os
# import requests
from dotenv import load_dotenv
# import aiohttp
# import aiofiles
# import logging
# logging.basicConfig(level=logging.INFO)
import cogs.whiskey
from colorama import Fore, Back, Style
bot = commands.Bot(command_prefix="$", intents=disnake.Intents.all())
ct = datetime.datetime.now()
guild_ids = []
print('Starting Bot')
print('Connecting to Discord API.')
print('Please Wait')
# Add Cogs
# bot.load_extension('cogs.social')
# bot.load_extension('cogs.chat_room_managment')
# bot.load_extension('cogs.socialv2')
# bot.load_extension('cogs.database')
# bot.load_extension('cogs.embd')
bot.load_extension('cogs.developerfeatures')
bot.load_extension('cogs.events')
print(Fore.YELLOW + '[✓]' + '[Developer Features Cog] ' + Fore.GREEN + 'Loading Complete' + Fore.WHITE)
Okay, looks like you're not subclassing then
You can bind the data using bot.var_name = ...
@sick birch so what should I do rn
Of course replace ... with actual data
Not sure, give me a sec to think
Ok
Well okay I get why it's sending a message every time
?
It sends a message every single message, as long as the user has a record in the database:
if not xp or not level:
...
else:
...
await message.channel.send(f"{author.mention} has leveled up to level **{level}**!")
Ah so basically add a else : ye ?
Not quite, you want to add an if statement detailing when the message should be sent
It’s meant to be sent when the user earned a level
Yes, so it should be sent when you UPDATE the database as well
Btw do u know why it says level 0 all the time ?
It takes 100 XP to get to one level right?
So it may take a while of you sending random messages
ok ill be sure to try that
does that go in the main file?
You just need to move that line to the part where you update the database with the user's new level
Preferably, yes
if xp >= 100:
level += 1
await client.db.execute("UPDATE levels SET level = ? WHERE user = ? AND guild = ?",
(level, author.id, guild.id,))
await client.db.execute("UPDATE levels SET xp = ? WHERE user = ? AND guild = ?",
(0, author.id, guild.id,))
await client.db.commit()
await message.channel.send(f"{author.mention} has leveled up to level **{level}**!")```
thats my if statement
i didnt change anything
it looks different from the pastebin
ye its the same tho
if this helps?
i get errors if i indent them more
What errors?
if xp >= 100 looks right?
indent errors lmao
Hm?
Those are the easiest to fix
The end goal is to get everything inside the if statement
okay , if u say so
isnt it gonna be triggered every time if the xp is above or equal to 100.....there's no point, its gonna perform the same task over and over
Isn't that the point though? If the XP is greater than or equal to 100, you should increment the level by 1?
I think I see what you're saying - you might want to reset XP back to 0 after that
.....then how do you get to the next levels....
I'm not quite following
nvm
Any errors?
uhhh i see Property 'guilds' cannot be set
guildz = os.getenv('GUILDS')
bot = commands.Bot(command_prefix="$", intents=disnake.Intents.all())
bot.guilds = guildz
mm
I mean, if xp >= 100 checks if the xp is greater than or equal to 100, and if it is above hundred every time, its gonna add a new level after every message
XP is reset to 0 when xp >= 100 though
oh i see
It's not clear and hidden in the query, so I see where you're coming from
i probially f'ed this up
Ah okay, I thought you could do that. Subclassing would fix that issue
class MyBot(commands.Bot):
def __init__(self, guilds, ...):
self.guilds = guilds
super().__init__(command_prefix="...", ...)
bot = MyBot(guilds=...)
Already did, move it into the if statement
i used the quick fix feature and it made a property. im going to try that
So just indent them a bit ye?
umm i dont understand whats going on there. could you use comments to explain what is going on. also whats super() do
@bot.command()
async def setapikey(ctx, apikey):
cfg = {}
with open("config.json", "r") as f:
cfg = json.load(f)
cfg[str(ctx.guild.id)] = apikey
with open("config.json", "w") as f:
json.dump(cfg, f, indent=4)
await ctx.author.send(f"Successfully set the api key to {apikey}")```
sending that in a public message is dangerous. maybe dming the bot would be safer
yep i'll do that instead but im testing the file writing for now
and my issue is in file writing as well
so if u help it'd be sexy
I don't know much so ima let the experts help lol
Does all that go in the main bot file?
@sick birch hey
can someone confirm if everything is inside of the if statement
or nah
OMG W
MY EVENT WORKS IT DOES THE LEVELS
I put everything in the if statement
Whoever helped me thanks the event works
But my command doesn’t , can yall help me ?
oof can you put the code here
YES
No problem
Great things take time I’m greatful I fixed my event atleast
@client.command(aliases=['lvl', 'rank', 'r'])
async def level(ctx, member: discord.Member = None):
member = member or ctx.author
async with client.db.execute("SELECT xp FROM levels WHERE user = ? AND guild = ?",
(member.id, ctx.guild.id,)) as cursor:
xp = await cursor.fetchone()
async with client.db.execute("SELECT xp FROM levels WHERE user = ? AND guild = ?",
(member.id, ctx.guild.id,)) as cursor:
level = await cursor.fetchone()
if not xp or not level:
await client.db.execute("INSERT INTO levels (level, xp, user, guild) VALUES (?, ?, ?, ?)",
(0, 0, member.id, ctx.guild.id,))
await client.db.commit()
try:
xp = xp[0]
level = level[0]
except TypeError:
xp = 0
level = 0
em = discord.Embed(title=f"{member.name}'s level", description=f"Level: `${level}`\nXP: `{xp}`")
await ctx.send(embed=em)```
wait
what part is not working
the command lol
import disnake
from disnake.ext import commands
from colorama import Fore, Back, Style
from datetime import datetime
import time
#below are two date time functions that have different functions but one of them adds to the other durring startup
start_time = datetime.now()
mytime = time.localtime()
if mytime.tm_hour < 12:
timeofday = 'AM'
else:
timeofday = 'PM'
class events(commands.Cog):
"""Useful Features for Bot Development."""
def __init__(self, bot: commands.Bot):
self.bot = bot
print('Loading Events cog')
@commands.Cog.listener()
async def on_ready(self):
guild_ids = self.bot
print(Fore.GREEN + 'Connected!')
print('Bot is ready!' + Fore.WHITE)
print(Fore.CYAN + 'Waiting For Commands' + Fore.WHITE)
embed = disnake.Embed()
embed.title = f"**Online**"
embed.set_footer(text="Logging System")
embed.set_author(name='WhiskeyBot', icon_url=f"{self.bot.user.avatar}")
embed.description = f"""**Bot Startup and Information**
Start Time: `{datetime.now().strftime('%b-%d-%Y at %I:%M:%S')} {timeofday}`
Current Uptime: <t:{round(datetime.timestamp(start_time))}:R>
Bot account: `{self.bot.user.name}`
Bot ID: `{self.bot.user.id}`
Guilds: `{len(self.bot.guilds):,}`
Users: `{len(list(self.bot.get_all_members()))}`
Disnake Version: `{disnake.__version__}`
Loaded Cogs: `{list(self.bot.cogs)}`
Developer: `whiskeythefox#7339`
"""
GUILD_ID = 798726719573065749
CHANNEL_ID = 798726720181633047
location = self.bot.get_guild(GUILD_ID).get_channel(CHANNEL_ID)
await location.send(embed=embed)
@commands.slash_command(name="uptime", guild_ids=guild_ids)
@sick birch ^
Did I do that right?
did you ask earlier?
ok someone else did lmao
idk but are you trying to create a custom help command?
Ok 1 sec
@flint isle my command aint working if u was interested
no, you don't want to do anything in on_ready
YO I fixed my event
await client.process_commands(message) should be moved one indentation level left
ye i did that already
finally
i need help fixing my command tho no responses or errors
and even stores and levels up properly
event gives me peace now xd
since you put the process_commands in the right place, the commands should respond
the level command doesnt tho
wanna inspect it?
@client.command(aliases=['lvl', 'rank', 'r'])
async def level(ctx, member: discord.Member = None):
if member is None:
member = ctx.author
async with client.db.execute("SELECT xp FROM levels WHERE user = ? AND guild = ?",
(member.id, ctx.guild.id,)) as cursor:
xp = await cursor.fetchone()
async with client.db.execute("SELECT level FROM levels WHERE user = ? AND guild = ?",
(member.id, ctx.guild.id,)) as cursor:
level = await cursor.fetchone()
if not xp or not level:
await client.db.execute("INSERT INTO levels (level, xp, user, guild) VALUES (?, ?, ?, ?)",
(0, 0, member.id, ctx.guild.id,))
await client.db.commit()
try:
xp = xp[0]
level = level[0]
except TypeError:
xp = 0
level = 0
em = discord.Embed(title=f"{member.name}'s level", description=f"Level: `${level}`\nXP: `{xp}`")
await ctx.send(embed=em)```
seems fine at first sight
why are you trying to index int and then catch it???? 
you should indent left from try: command all below
only reason why you might never get a response is if if not xp or not level: is always False...
then ofc it won't ever send an embed
xp is fetch result, it should be tuple of results
what shall i do then
also, your SELECT statement doesn't make much sense
you can select multiple columns at once
as well as update
you don't have to make 2 db executions of that
what do i change
Does someone mind looking over my code? I have a cog with a few commands which work, a event which doesn't seem to be working and a task loop which I don't think is working. I'm not getting any errors so I'm thinking I have a logic issue that I just can't find.
The code: https://paste.pythondiscord.com/rorenuxega.py
hmm
Traceback (most recent call last):
File "C:\Users\Andy\PycharmProjects\WhiskeyBotMain\wb.py", line 2, in <module>
from disnake.ext import commands
File "C:\Users\Andy\AppData\Local\Programs\Python\Python310\lib\site-packages\disnake\ext\commands\__init__.py", line 12, in <module>
from .bot import *
File "C:\Users\Andy\AppData\Local\Programs\Python\Python310\lib\site-packages\disnake\ext\commands\bot.py", line 57, in <module>
class Bot(BotBase, InteractionBotBase, disnake.Client):
File "C:\Users\Andy\AppData\Local\Programs\Python\Python310\lib\site-packages\disnake\ext\commands\bot.py", line 183, in Bot
@guilds.setter
NameError: name 'guilds' is not defined
first verify if the command ever gets executed by printing something in it
remove one indentantion from try: to everything below
and how shall i do that?
ok
print("shit") first line
so move everything back once ye?
it broke after i subclassed my bot
from try:
yes
you don't want to make a help command like that
What is that help command
anyways, you forgot the command decorator
but you don't want to hardcode a help command
just read this
#discord-bots message
lol i sent him that origionally
I guess he just doesn't want to read
LETS GO
Lmao
ALL FIXED …..
show code
import disnake
from disnake.ext import commands
from colorama import Fore
from datetime import datetime
import time
#below are two date time functions that have different functions but one of them adds to the other durring startup
from wb import guild_ids
start_time = datetime.now()
mytime = time.localtime()
if mytime.tm_hour < 12:
timeofday = 'AM'
else:
timeofday = 'PM'
class events(commands.Cog):
"""Useful Features for Bot Development."""
def __init__(self, bot: commands.Bot):
self.bot = bot
print('Loading Events cog')
@commands.Cog.listener()
async def on_ready(self):
guild_ids = self.bot
print(Fore.GREEN + 'Connected!')
print('Bot is ready!' + Fore.WHITE)
print(Fore.CYAN + 'Waiting For Commands' + Fore.WHITE)
embed = disnake.Embed()
embed.title = f"**Online**"
embed.set_footer(text="Logging System")
embed.set_author(name='WhiskeyBot', icon_url=f"{self.bot.user.avatar}")
embed.description = f"""**Bot Startup and Information**
Start Time: `{datetime.now().strftime('%b-%d-%Y at %I:%M:%S')} {timeofday}`
Current Uptime: <t:{round(datetime.timestamp(start_time))}:R>
Bot account: `{self.bot.user.name}`
Bot ID: `{self.bot.user.id}`
Guilds: `{len(self.bot.guilds):,}`
Users: `{len(list(self.bot.get_all_members()))}`
Disnake Version: `{disnake.__version__}`
Loaded Cogs: `{list(self.bot.cogs)}`
Developer: `whiskeythefox#7339`
"""
GUILD_ID = 798726719573065749
CHANNEL_ID = 798726720181633047
location = self.bot.get_guild(GUILD_ID).get_channel(CHANNEL_ID)
await location.send(embed=embed)
@commands.slash_command(name="uptime", guild_ids=guild_ids)
async def uptime(self, ctx):
...
def setup(bot):
bot.add_cog(events(bot))
```
where is the guild setter?
i think thats an internal error for disnake
ah wait, i misread it. Hold on
mm i pasted the wrong code :/
yo i fixed it all GG
still not optimized, but cool
now time for rank card finally
hey where should i start with when looking to make a simple discord bot?
also does experience matter? I have about a week of experience
you should at least know python OOP basics
what is oop?
im not sure what the problem is, did u make the super call after subclassing?
lol, bad start
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: Forbidden: 403 Forbidden (error code: 50003): Cannot execute action on a DM channel
@bot.command()
async def setapikey(ctx, apikey):
if isinstance != (ctx.channel, discord.channel.DMChannel):
await ctx.message.delete()
await ctx.author.send("WARNING! You can not use this command in the server because it might result in your api key getting leaked!\nReGen your api key and set your api here!")
elif isinstance(ctx.channel, discord.channel.DMChannel):
with open('config.json', 'r') as f:
cfg = json.load(f)
cfg[str(ctx.author.id)] = apikey
with open('config.json', 'w') as f:
json.dump(cfg, f)
await ctx.send(f"Successfully set the api key to {apikey}")
happens when i use the command in my dms
yeah im not super experienced, ill check this out ty
if isinstance != (ctx.channel, discord.channel.DMChannel):

you can't delete a message in DM's
you should READ YOUR ERROR, then you should've known EXACTLY what line caused it
oh hold up
im not trying to delete a message in dms, this is when the channel is not a dms
and its if not isinstance(ctx.channel, discord.channel.DMChannel)
even better
if ctx.channel.type == "private":
#...
else:
#...```
that fixed it, ty
and also use ELSE pls
import disnake
from disnake.ext import commands
import datetime
import os
# import requests
from dotenv import load_dotenv
# import aiohttp
# import aiofiles
# import logging
# logging.basicConfig(level=logging.INFO)
load_dotenv()
guilds = os.getenv('GUILDS')
import cogs.whiskey
from colorama import Fore
load_dotenv()
class MyBot(commands.Bot):
def __init__(self, guilds):
self.guilds = guilds
super().__init__(command_prefix="$", intents=disnake.Intents.all())
bot = commands.Bot(command_prefix="$")
ct = datetime.datetime.now()
guild_ids = []
print('Starting Bot')
print('Connecting to Discord API.')
print('Please Wait')
# Add Cogs
# bot.load_extension('cogs.social')
# bot.load_extension('cogs.chat_room_managment')
# bot.load_extension('cogs.socialv2')
# bot.load_extension('cogs.database')
# bot.load_extension('cogs.embd')
bot.load_extension('cogs.developerfeatures')
bot.load_extension('cogs.events')
print(Fore.YELLOW + '[✓]' + '[Developer Features Cog] ' + Fore.GREEN + 'Loading Complete' + Fore.WHITE)
and?
you've made a subclass for your bot, but you're never using it...
class Shit(commands.Bot):
# ...
bot = Shit(...)```
im trying pass a var to the cogs
sure
just
bot = MyBot(guild_ids)
you've already hardcoded the command prefix in the init, so no need to pass that anymore
Im trying to make a discord bot that sends a roblox username and then deletes the username from the file but I dont know how to delete the text!
CODE:
await ctx.author.send(random_line('roblox.txt') + "\nFORMAT: Username:Password")
random_line('roblox.txt').delete()
it selects a random line and says it in a server
but how do I remove the line so it will never be said again?
I know you're trying to make some sort of giveaway or whatever, but you should definitely use a database for that
No, Gen bot
you put accounts in and when someone runs a command like $roblox it sends them a roblox account from a huge txt file all I need to know is how do I delete that account from the txt after its been sent
you want to use a database for these kind of things
you have to switch from " to ' inside an f string ofc
user_data["level"] => user_data['level']
same goes for the rest of the user data shit
Fr?
First time damn
I never used em
it's just because the f string messes with it
it thinks it's already the end of the string if you use "
or you can just use singular ' for the outside of the f string
f'My name {person["name"]} and my age {person["age"]}'
teach me how?
C:\Users\Andy\virenv\Scripts\python.exe C:/Users/Andy/PycharmProjects/WhiskeyBotMain/wb.py
Traceback (most recent call last):
File "C:\Users\Andy\PycharmProjects\WhiskeyBotMain\wb.py", line 2, in <module>
from disnake.ext import commands
File "C:\Users\Andy\AppData\Local\Programs\Python\Python310\lib\site-packages\disnake\ext\commands\__init__.py", line 12, in <module>
from .bot import *
File "C:\Users\Andy\AppData\Local\Programs\Python\Python310\lib\site-packages\disnake\ext\commands\bot.py", line 57, in <module>
class Bot(BotBase, InteractionBotBase, disnake.Client):
File "C:\Users\Andy\AppData\Local\Programs\Python\Python310\lib\site-packages\disnake\ext\commands\bot.py", line 183, in Bot
@guilds.setter
NameError: name 'guilds' is not defined
welp the internal error is still here
learn SQL first in #databases
you have to FIRST do the super().__init shit
THEN do the self.guilds = guilds
you want to add own variable (property) to bot? the one named "guilds" is already used
should i just do env_guilds
i wanna it except this specific error User is at daily alt limit. how?
why did you say (property) ?
for the var
because objects have properties and methods
doesnt the custom variables get contained in the random amount of kwargs inside of the class's init?
I am making a discord bot and I have alot of phrases I want to use in a txt file but I never want the same phrase to be said twice
So I need to delete the phrase from a txt file any ways how?
i'm not sure of that
!e
class Bot:
def __init__(self, **kwargs):
...
bot = Bot()
bot.var = 1
print(bot.var)
@slate swan :white_check_mark: Your eval job has completed with return code 0.
1
guys i have an error
Command raised an exception: AttributeError: 'str' object has no attribute 'url'
youre trying to use a attribute named url that doesnt exist in the str class as said in the error
I am making a discord bot and I have alot of phrases I want to use in a txt file but I never want the same phrase to be said twice
So I need to delete the phrase from a txt file any ways how?
idk lemme show my code
still, you need a database
step away from your txt
user_data = {
"name": f"{member.name}#{member.discriminator}",
"xp": xp,
"level": level,
"next_level_xp": 100,
"percentage": xp,
}
background = Editor(Canvas((900, 300), color="#141414"))
profile_picture = await load_image_async(str(member.avatar.url))
profile = Editor(profile_picture).resize((150, 200)).circle_image()
poppins = Font.poppins(size=40)
poppins_small = Font.poppins(size=30)
card_right_shape = [(600, 0), (750, 300), (900, 300), (900, 0)]
background.poppins(card_right_shape, color="#FFFFFF")
background.paste(profile, (30, 30))
background.rectangle((30, 220), width=650, height=40, color="#FFFFFF")
background.bar((30, 220), maw_width=650, height=40, percentage=user_data["percentage"], color="#FFFFFF", radius=20,)
background.text((200, 40), user_data["name"], font=poppins, color="FFFFFF")
background.rectangle((200, 100), width=350, height=2, fill="#FFFFFF")
background.text(
(200, 130),
f"Level - {user_data['level']} | XP - {user_data['xp']}/{user_data['next_level_xp']}",
font = poppins_small,
color = "#FFFFFF",
)
file = discord.File(fp=background.image_bytes, filename="levelcard.png")
await ctx.send(file=file)```
I dont
My friend made one
and it worked but he wont send me it
if you want to copy his bad implementation, sure
I have over 300k phrases
just checking words in a txt file is fine but manipulating the data, mhm no good
have you ever read an error thoroughly?
ye lol
its possible
well, the error should tell you EXACTLY what line causes the error...
ofc it is, but I can eat soup with a fork too
never said it was? but should it be done? No.
well, I see it already
why are you making it a string?
im pretty sure the url property returns a string already
is this better
@slate swan You're gonna find yourself in a load of trouble here, trying to evade the rules
fuvvvck off
profile_picture = await load_image_async(member.avatar.url))```
loading the image can even be done through the .read() method lol
:/
is this fine ?
leave me alone
import disnake
from disnake.ext import commands
import datetime
import os
# import requests
from dotenv import load_dotenv
# import aiohttp
# import aiofiles
# import logging
# logging.basicConfig(level=logging.INFO)
import cogs.whiskey
from colorama import Fore
load_dotenv()
class MyBot(commands.Bot):
def __init__(self, guilds):
self.guilds = guilds
super().__init__(command_prefix="$", intents=disnake.Intents.all(), env_guild = os.getenv('guilds'))
bot = commands.Bot(command_prefix="$")
guilds = os.getenv('GUILDS')
# bot = commands.Bot(command_prefix="$", intents=disnake.Intents.all())
ct = datetime.datetime.now()
guild_ids = []
print('Starting Bot')
print('Connecting to Discord API.')
print('Please Wait')
you're making it harder than it is
so all i do is .read and thats it?
why are you making a class and not using it?
you should read the docs about this
already said that many times, but he just won't listen
even gave examples
i dont know how to . im completly confused
this is so sad, when i was a beginner i wanted to learn so much things while everyone here doesnt care and they just go by "it works"😔
i will scroll back up and find them and look again
profile_picture = await load_image_async(member.avatar.url)```
bruh i dont see the error in this , still gives the error
or just picking up way too big starter projects is just doomed to fail
You're creating instance of commands.Bot
bot = commands.Bot(command_prefix="$")
But you have a custom class, use it instead:
bot = MyBot(guilds)
!d discord.Member.avatar
property avatar```
Equivalent to [`User.avatar`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User.avatar "discord.User.avatar")
that happened to me, it didnt end well thats for sure
stick and stones, rizzy
check the methods of that
the docs command has 41 packages you need to specify which one
!d discord.User.avatar
property avatar```
Returns an [`Asset`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Asset "discord.Asset") for the avatar the user has.
If the user does not have a traditional avatar, `None` is returned.
If you want the avatar that a user has displayed, consider [`display_avatar`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User.display_avatar "discord.User.display_avatar").
does someone mind taking a look at my code as I have, either, a task not running or a event not getting called.
throws sticks and stones at you
?
what is this a role play server?

shut up
ill rather not
Ill slap you like your dad does Oh wai-
!ot
Off-topic channel: #ot2-never-nester’s-nightmare
Please read our off-topic etiquette before participating in conversations.
back on topic lmao
import disnake
from disnake.ext import commands
import datetime
import os
# import requests
from dotenv import load_dotenv
# import aiohttp
# import aiofiles
# import logging
# logging.basicConfig(level=logging.INFO)
import cogs.whiskey
from colorama import Fore
load_dotenv()
env_guilds = os.getenv('GUILDS')
class MyBot(commands.Bot):
def __init__(self, env_guilds):
self.guilds = env_guilds
super().__init__(command_prefix="$", intents=disnake.Intents.all(), env_guild = os.getenv('guilds'))
bot = MyBot(env_guilds)
ct = datetime.datetime.now()
guild_ids = []
``` Did i do the right?
user_data = {
"name": f"{member.name}#{member.discriminator}",
"xp": xp,
"level": level,
"next_level_xp": 100,
"percentage": xp,
}
background = Editor(Canvas((900, 300), color="#141414"))
profile_picture = await load_image_async(member.avatar.url)
profile = Editor(profile_picture).resize((150, 200)).circle_image()```whats wrong here
lol it got caught by the filter
can u help me
!tban 662420265866625074 14d inappropriate comments and behavior. really, consider whether you want to be a part of our community or not.
:incoming_envelope: :ok_hand: applied ban to @reef bluff until <t:1654378383:f> (13 days and 23 hours).
thank you mina!
user_data = {
"name": f"{member.name}#{member.discriminator}",
"xp": xp,
"level": level,
"next_level_xp": 100,
"percentage": xp,
}
background = Editor(Canvas((900, 300), color="#141414"))
profile_picture = await load_image_async(member.avatar.url)
profile = Editor(profile_picture).resize((150, 200)).circle_image()``` whats wrong here, anyone
is dis better
error handler to push a message. idk how to build one lol tho
ok, first of all, what dpy version are you on?
don't forget to add an
else: raise error in the error handler, you're hiding all the other errors
i fixed it
it was member.avatar_url
so you're on v 1.7.3
Wait a sec wouldn't the self.guilds break the bot
yes, we already discussed this my guy
Oh I didn't understand it originally but when I reread the code that was word wrapped I saw that. Would I remove the line with self.guilds or replace it with something else
just use variable name that doesn't exist already
is that good or bad?
that's fine in your case
and also, EVERY guidance in this channel matters, don't just "ignore and ask again later on"
Ah so like testserver inplace of the self.guilds
Yeah my attention was split between this and something else so I missed it or got confused. Sorry
just call it
custom_guild_ids or whatever
Ok
debug my guy, debug
Huh
just print the xp right before you'd use a database command or whatever to verify that is in fact all the correct values
you didn't correct second one
if rand == 1:
xp = random.randint(1, 3)
should be xp += random.randint(1, 3)
new feature it costs 1xp to check rank
Will this fix it then ?
it should
Ok
I'm busy, I won't for now
and now i need help refrencing it in the cog lol.
!paste
could you look at this and let me know if anything is broke?
https://paste.pythondiscord.com/adesawitam
in a cog, it's as easy as
self.bot.custom_guild_ids
i think custom_guilds = env_guilds should be self.custom_guilds = env_guilds, in MyBot class
same for guild_ids = bot.custom_guilds in a cog, self.guild_ids = bot.custom_guilds
hello
you don't have to define guild_ids again in the cog, let me tell you that
good host for bots to suggest me?
netcup
is it free or not
No vps aren't free
and free?
I don't recommend any "free" hosting solutions, sorry.
You can look for trails like AWS.
where did i set it again? if you could paste the line here ill look at where it is lol
just don't touch your cog's init, only use it for the self.bot = bot
Then you'd be surprised of where I touch the cog's init 😏


XD
calls 911
and your subclassed bot's init should look like
class Shit(commands.Bot):
def __init__(custom_guild_ids, *args, **kwargs):
super().__init__(*args, **kwargs)
self.custom_guild_ids = custom_guild_ids```
if this isn't a spoonfeed, I don't know what is
9/10 use cog_load.
he just wants to add that stinky botvar in every cog, because else he thinks he can't access it, which isn't true
once defined in the main class, you can just access that variable wherever an instance of your bot class is
Python allows you to set custom attributes to most objects, like your bot! By storing things as attributes of the bot object, you can access them anywhere you access your bot. In the discord.py library, these custom attributes are commonly known as "bot variables" and can be a lifesaver if your bot is divided into many different files. An example on how to use custom attributes on your bot is shown below:
bot = commands.Bot(command_prefix="!")
# Set an attribute on our bot
bot.test = "I am accessible everywhere!"
@bot.command()
async def get(ctx: commands.Context):
"""A command to get the current value of `test`."""
# Send what the test attribute is currently set to
await ctx.send(ctx.bot.test)
@bot.command()
async def setval(ctx: commands.Context, *, new_text: str):
"""A command to set a new value of `test`."""
# Here we change the attribute to what was specified in new_text
bot.test = new_text
This all applies to cogs as well! You can set attributes to self as you wish.
Be sure not to overwrite attributes discord.py uses, like cogs or users. Name your attributes carefully!
C:\Users\Andy\virenv\Scripts\python.exe C:/Users/Andy/PycharmProjects/WhiskeyBotMain/wb.py
Traceback (most recent call last):
File "C:\Users\Andy\PycharmProjects\WhiskeyBotMain\wb.py", line 2, in <module>
from disnake.ext import commands
File "C:\Users\Andy\AppData\Local\Programs\Python\Python310\lib\site-packages\disnake\ext\commands\__init__.py", line 12, in <module>
from .bot import *
File "C:\Users\Andy\AppData\Local\Programs\Python\Python310\lib\site-packages\disnake\ext\commands\bot.py", line 57, in <module>
class Bot(BotBase, InteractionBotBase, disnake.Client):
File "C:\Users\Andy\AppData\Local\Programs\Python\Python310\lib\site-packages\disnake\ext\commands\bot.py", line 183, in Bot
@guilds.setter
NameError: name 'guilds' is not defined
i still dont know what i broke
code?