#discord-bots
1 messages Β· Page 1026 of 1
And specifically {0.domething} when using it only once, which loses the usage of actually using 0
ok so it would be an option that would work?
u need to modify it with ur brain instead of control c v blindly
In my opinion it just straight up shows how not to make a bot.
async def start_loop(self):
await self.api.start_loop()
print("Post Count")
async def setup(bot):
cog = DiscordListsPost(bot)
await bot.add_cog(cog)
await cog.start_loop()``` ```py
Extension 'cogs.api' raised an error: AttributeError: loop attribute cannot be accessed in non-async contexts. Consider using either an asynchronous main function and passing it to asyncio.run or using asynchronous initialisation hooks such as Client.setup_hook``` I seem to still be having an issue with my API can someone help me please
huh
wait but what does 0 or whatever that symbol is mean
?
0 means the number 0
and what symbol are u referring to
tf is this
print('We have logged in as {0.user}'.format(client))
formatting string without formatter
use f strings, easier
To be fair
ya
.format is old habit for me
yeah ik but ig they wrote it back when 3.6 hasn't been released
!d format
instead of ' ' + ' ' + ' ' + ' ' + ' ' + ' '
!f-strings
Creating a Python string with your variables using the + operator can be difficult to write and read. F-strings (format-strings) make it easy to insert values into a string. If you put an f in front of the first quote, you can then put Python expressions between curly braces in the string.
>>> snake = "pythons"
>>> number = 21
>>> f"There are {number * 2} {snake} on the plane."
"There are 42 pythons on the plane."
Note that even when you include an expression that isn't a string, like number * 2, Python will convert it to a string for you.
str.format ? ig
Just regex it kapp
so what does 0.user mean
It takes the 0th argument from what's in .format(x)
its jus a placeholder for a value which is filled using the format function
oh ok
and u count from 0 instead of 1
Useful if you want to use the element multiple times but with a different attribute
..
And to be fair, there are use cases for "{x.foo} something something {x.bar}".format(x)
hihi
Hey π
going valorant byebye
yo i think i should clean up my code.. how do i use cogs for cmds or whatever
like if i want mute cmd in mute file how make that work
i just got 3 times
get better
don't make a command per cog, thats overkill
i saw an odin ace today
well my main file is 830 lines
i need to do at least smth
Nice
im trying to
they asked how to use cogs
well im mostly asking how i can organize my cmds into diff files
a mute command in mute file
20 files for 20 commands...?
I use 1 file for my giv cmd
Cuz it's 300+ lines
i just want like a file for moderation cmds, then giveaway cmds, then fun cmds, etc
and if im doing a list too
do you have a repo?
would i do from (file name) import (whatever i need to import)?
Ash every msg bl curv line
Yes
π
If u want
ah cool, sure
I code but I code bad sometimes
understandable and relatable
Waif I'll open my pc real quick
I mean you could sent it later whenever you would be free
# cog_file.py
from discord.ext import commands
class MyCog(commands.Cog):
@commands.command()
async def command (self, context):
... #this is command
@commands.Cog.listener()
async def on_ready(self):
... # this is an event
def setup(bot):
bot.add_cog(MyCog())
``` this is an example for a very basic cog
you can add it in your bot using `bot.load_extension("cog_file")` ( v1.7.3)
You can make the commands in a cog or use @lavish micamands.command(). Then create a setup function (async if on discord.py v2) with one parameter bot then use bot.add_cog or bot.add_command to add the commands
This is called extensions
thx
Lol
lol
Then load the extension with bot.load_extension(βfileβ)
i could name MyCog smth else right
Yes
anything you want to
ok i was just quizzing you guys to make sure you know
you passed good job
lmaoooo
dose anybody know how to fix this?
i definitely knew that
its fine xD
and i definitely know how to spell definitely
i can use client instead of bot right
no.
i opened my code from like 3 weeks ago, i didnt understand anything ... π
you can, but why would you call a "bot" a "client"
Lol
Just commands.Bot
because of where my gaming culture came from
i write shit like this
table_data = [
data for i, j in zip(soup.find_all('th')[1:15], soup.find_all('td')[1:15])
if '...' not in (data := {
'inline': False,
'name': i.text if i.text else '...',
'value': '...' if valid_chars.match(j.text) else j.text if j.text else '...'
}
).values()
]
ofc i wont understand
that's why don't use esoteric python

imagine making raw payloads for embeds
if im doing multiple cmds do i need to do multiple class definition thingys
that scrapes this part of the wiki page
just embed.to_dict()
thx for the free code
welcome
else j.text if j.text else '...' i can replace this with else j.text or '...' π
no, more commands.command decorator
ok
!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.
would i put error handler codes in that cog file
async def cog_command_error(ctx,error):
its fun lol
async def start_loop(self):
await self.api.start_loop()
print("Post Count")
async def setup(bot):
cog = DiscordListsPost(bot)
await bot.add_cog(cog)
await cog.start_loop()``` ```py
Extension 'cogs.api' raised an error: AttributeError: loop attribute cannot be accessed in non-async contexts. Consider using either an asynchronous main function and passing it to asyncio.run or using asynchronous initialisation hooks such as Client.setup_hook``` I seem to still be having an issue with my code can someone help me please
back
but Unreadable π
What is self.api
It goes with an API library
Afaik you start loop non asynchronously even in dpy 2.0
idk what im doing
If it is not dpy 2.0 loop, then overwrite setup_hook method of your bot subclass
How?
class MyBot(commands.Bot):
async def setup_hook(self):
# here```
What do I put in set up hook?
You should bring your api out of the cog into the bot if it's possible
It's not
What makes it be?
im kinda dum, how would i add the top cmd into the bottom code
I can't imagine a situation that would make it impossible to access
Copypasting code is dumb indeed
im just trying to transfer my code from my main file into different files to organize it all
Ok
:/
idk i just feel like this is a basic thing that i just dont know how to do
@keen mural here you can find examples for disnake, for dpy 1.7 it's almost the same https://tutorial.vcokltfre.dev/tutorial/intermediate/disnake/11-cogs/
A tutorial to help you make better Discord bots.
Got to make a task loop every 12 hours
Something like
from discord.ext import tasks
@tasks.loop(hours=12.0)
async def my_task():
print("Do stuff here")
my_task.start()
@slate swan how do i add a check decorator to a command for guild permissions π
!d discord.ext.commands.has_guild_permissions
@discord.ext.commands.has_guild_permissions(**perms)```
Similar to [`has_permissions()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.has_permissions "discord.ext.commands.has_permissions"), but operates on guild wide
permissions instead of the current channel permissions.
If this check is called in a DM context, it will raise an
exception, [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage").
New in version 1.3.
wrong channel?
For your guys bot @unkempt canyon do you guys have a help command in cogs form?
why does this command mute but replies to the message after 10 seconds?
# mute
@commands.command()
@commands.has_permissions(manage_messages=True)
async def mute(self, ctx, member: discord.Member, *, reason = "No reason provided"):
guild = ctx.guild
mutedRole = discord.utils.get(guild.roles, name="muted")
emb = discord.Embed(description=f":white_check_mark:Member **{member.name}** has been muted!", colour = discord.Color.gold())
emb.add_field(name="Moderator:", value=f"{ctx.author.mention}")
embed = discord.Embed(title=f"You were muted on the server {ctx.guild.name}", colour=discord.Color.gold())
if not mutedRole:
mutedRole = await guild.create_role(name="muted")
for channel in guild.channels:
await channel.set_permissions(mutedRole, speak=False, send_messages=False, read_message_history=True, read_messages=True)
await member.add_roles(mutedRole, reason=reason)
await ctx.reply(embed=emb)
await member.send(embed=embed)```
!src help
An interactive instance for the bot help command.
you can see it there
I saw do you have the ! Paste there?
guys can someone help me
File "C:\Users\Dom\Desktop\python bot\main.py", line 29, in on_ready
bot.load_extension('cogs.leveling')
AttributeError: 'Command' object has no attribute 'load_extension'```
should i show code?
ya
Sorry, an unexpected error occurred. Please let us know!
AttributeError: 'TagIdentifier' object has no attribute 'qualified_name'
ah it's a tag
await coro(*args, **kwargs)
File "C:\Users\Dom\Desktop\python bot\main.py", line 29, in on_ready
bot.load_extension('cogs.leveling')
AttributeError: 'Command' object has no attribute 'load_extension'
this is my error\
you want the code that handles the tags or where you can find the tag paste?
Its bot instance
Not command
Show ur bot var
ill show my cog file
Ok
ugh
my discord is undefined i think maybe thats why
idk
from discord.ext import commands
import json
class leveling(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.Cog.listener()
async def on_ready(self):
print('leveling.py has been loaded')
@commands.Cog.listener()
async def on_message(self,message):
with open('users.json', 'r', encoding='utf8') as f:
user = json.load(f)
try:
with open('users.json', 'w', encoding='utf8') as f:
user[str(message.author.id)]['xp'] = user[str(message.author.id)]['xp']+1
lvl_start = user[str(message.author.id)]['level']
lvl_end = user[str(message.author.id)]['xp'] ** (1.5/4)
if lvl_start < lvl_end:
user[str(message.author.id)]['level'] = user[str(message.author.id)]['level']+1
lvl = user[str(message.author.id)]['level']
await message.channel.send(f"GG, {user.mention} you have leveled up , you are now level {lvl}")
json.dump(user, f, sort_keys=True, indent = 4, ensure_ascii=False)
return
json.dump(user, f, sort_keys=True, indent = 4, ensure_ascii=False)
except:
with open('users.json', 'w', encoding='utf8') as f:
user = {}
user[str(message.author.id)] = {}
user[str(message.author.id)]['level'] = 0
user[str(message.author.id)]['xp'] = 0
json.dump(user, f, sort_keys=True, indent = 4, ensure_ascii=False)
def setup(bot):
bot.add_cog(leveling(bot))```
Like where that paste code sic
paste is a tag, read the .md file
i just sent that -_-
@lightbulb.add_checks(lightbulb.has_guild_permissions())

Lightbulb has guild perms lol
tried that, what do i add in the guild permissions? π
The permissions....?
i showed my code
huh? ur getting an imoprt error?
i think
# mute
@commands.command()
@commands.has_permissions(manage_messages=True)
async def mute(self, ctx, member: discord.Member):
guild = ctx.guild
mutedRole = discord.utils.get(guild.roles, name="muted")
emb = discord.Embed(description=f":white_check_mark:Member **{member.name}** has been muted!", colour = discord.Color.gold())
emb.add_field(name="Moderator:", value=f"{ctx.author.mention}")
embed = discord.Embed(title=f"You were muted on the server {ctx.guild.name}", colour=discord.Color.gold())
em = discord.Embed(title=f"Member already muted!", colour=discord.Color.gold())
if not mutedRole:
mutedRole = await guild.create_role(name="muted")
elif mutedRole in member.roles:
await ctx.reply(embed=em)
for channel in guild.channels:
await channel.set_permissions(mutedRole, speak=False, send_messages=False, read_message_history=True, read_messages=True)
await member.add_roles(mutedRole)
await ctx.reply(embed=emb)
await member.send(embed=embed)```
so lemme explain
async def on_ready():
change_status.start()
print('bot is ready')
bot.load_extension('cogs.leveling')``` this is in my main.py
who can help me?
can u show the error?
ok
who?
not u π
π©
bot.load_extension('cogs.leveling')
AttributeError: 'Command' object has no attribute 'load_extension'```
show where u defined bot
i have 2 cog files a cog file for reward.py but i have that setup and it works , i use it as a client , and the second one as bot
i just realized, ur using bot and client? why?
just use one...
can i have them all as client?
# mute
@commands.command()
@commands.has_permissions(manage_messages=True)
async def mute(self, ctx, member: discord.Member):
guild = ctx.guild
mutedRole = discord.utils.get(guild.roles, name="muted")
emb = discord.Embed(description=f":white_check_mark:Member **{member.name}** has been muted!", colour = discord.Color.gold())
emb.add_field(name="Moderator:", value=f"{ctx.author.mention}")
embed = discord.Embed(title=f"You were muted on the server {ctx.guild.name}", colour=discord.Color.gold())
em = discord.Embed(title=f"Member already muted!", colour=discord.Color.gold())
if not mutedRole:
mutedRole = await guild.create_role(name="muted")
elif mutedRole in member.roles:
await ctx.reply(embed=em)
for channel in guild.channels:
await channel.set_permissions(mutedRole, speak=False, send_messages=False, read_message_history=True, read_messages=True)
await member.add_roles(mutedRole)
await ctx.reply(embed=emb)
await member.send(embed=embed)```
wait so i can have them all as client
client doesn't have cog support iirc, use bot
client supports for my rewards.py
U have a command named bot
so what should i do
rename it ..
π
?
.
im so confused , can someone edit my code
we can't see the part of ur code which is causing problems, but anyways u have a @client.command() named bot which is causing problems
it mute instantly, but the message sends after 10 seconds
umm lemme check
all i could find
The last result
ye that
async def bot(ctx)
huh
Change the name of that function
so bot.add_cog - async def bot(ctx)
.....?
this
thats for my command
it works fine
when i change the async def it says bot is not defined
yep i see
@bot.event
async def on_message(message) :
if message.channel.id == 970895283250675813 :
data = message.content.split(" ")
user = re.sub("\D", "", data[4])
hehehe = str(bot.get_user(user) or await bot.fetch_user(user))
db[f'{hehehe.id}cooked_pogchop'] += 42
db[f'{hehehe.id}voteCount'] += 1
O my bots
hehehe = str(bot.get_user(user) or await bot.fetch_user(user))
why converting to string?
HEHEHE
oo ya
so now my error is bot is not defined
bot = commands.Bot(command_prefix = prefixxx, case_insensitive=True, activity=discord.Game(name="RPM", type=3))
```modify it urself
oh nice my cog file is working ,
now i just need to fix in main.py
the bot.load_extension part
so someone.
whats the issue huh?
can someone vote for this? im fixing vote rewards
bot is not defined
There's a thing called "test webhook"
my cog file is good now , but in main.py (bot is not defined) i had a client command and it had bot as function so it changed my code so ye
but im working on vote reward role
You don't need someone to actually vote, it sends similar request
I got a stroke reading this
Just press that button and it will send request just like you voted
okok
where "member is not muted"?
print mutedRole after you get it and see what it prints
@bot.event
async def on_message(message) :
if message.channel.id == 970895283250675813 :
data = message.content.split(" ")
user = re.sub("\D", "", data[4])
hehehe = bot.get_user(user) or await bot.fetch_user(user)
hehehe = str(hehehe.id)
db[f'{hehehe}cooked_pogchop'] += 42
db[f'{hehehe}voteCount'] += 1
I would recommend adding "not a dm channel" condition to your on_message but I am unsure how can this happen if you have channel id restricted
Well the error explains itself , you can't add_role() to a discord User, you need to get a Member object
If everything is inside your channel condition that's almost impossible to occur
Ig you have something outside
but how
?
!d discord.Guild.get_member
get_member(user_id, /)```
Returns a member with the given ID.
Changed in version 2.0: `user_id` parameter is now positional-only.
Do uk how to get the guild object right?
Lmao
bot.get_guild()
If your bot isn't intended to process messages from DMs just add this to the beginning of the event handler
if message.channel.type == discord.ChannelType.private:
return```
isinstance is better, isn't it?
Long time no see m8
Indeed
my brain rn: π₯
Comparison of enums is more obvious imho
How are you doing
Preferences
Yes
so what do i do now
This
huh
if message.channel.type == discord.ChannelType.private:
return
elif message.channel.id == 970895283250675813 :
data = message.content.split(" ")
user = re.sub("\D", "", data[4])
hehehe = bot.get_user(user) or await bot.fetch_user(user)
hehehe = str(hehehe.id)
db[f'{hehehe}cooked_pogchop'] += 42
db[f'{hehehe}voteCount'] += 1
```like this?
Yes but elif is unnecessary in this case
if also?
Just put 2 ifs
okok
How's game dev working for ya
but it doesnt fix the problem =.=
What problem did you have
here
This thing will basically ignore all DM messages
So you won't get User objects as authors
huh
hehehe = str(hehehe.id)
f strings can accept any type of objects
ext/automod.py lines 36 to 42
if (
message.author.bot
or message.channel.type == disnake.ChannelType.private
or len(message.content) == 0
or message.author.guild_permissions.manage_guild
or not message.channel.permissions_for(message.guild.me).send_messages
):```
!e
print(f'{10}, {10.1}, {"hello"}')
@paper sluice :white_check_mark: Your eval job has completed with return code 0.
10, 10.1, hello
?
u dont need to convert to str
Could you show your new code?
@bot.event
async def on_message(message) :
if message.channel.type == discord.ChannelType.private:
return
if message.channel.id == 970895283250675813 :
data = message.content.split(" ")
user = re.sub("\D", "", data[4])
hehehe = bot.get_user(user) or await bot.fetch_user(user)
hehehe = hehehe.id
db[f'{hehehe}cooked_pogchop'] += 42
db[f'{hehehe}voteCount'] += 1
@bot.event
async def on_message(message) :
if message.channel.type == discord.ChannelType.private:
return
if message.channel.id == 970895283250675813 :
data = message.content.split(" ")
user = re.sub("\D", "", data[4])
hehehe = bot.get_user(user) or await bot.fetch_user(user)
hehehe = hehehe.id
db[f'{hehehe}cooked_pogchop'] += 42
db[f'{hehehe}voteCount'] += 1
voteCount = db[f'{hehehe}voteCount']
if voteCount < 10:
role = message.guild.get_role(971310924478705695)
elif voteCount < 18:
role = message.guild.get_role(971310601668288512)
elif voteCount < 69:
role = message.guild.get_role(971311031555072020)
elif voteCount < 100:
role = message.guild.get_role(971311323658977281)
elif voteCount < 420:
role = message.guild.get_role(971311024051486742)
elif voteCount >= 420:
role = message.guild.get_role(971311028694577162)
else:
role = message.guild.get_role(905626727005454457)
await message.author.add_roles(role)
await bot.process_commands(message)
Do you have members intent or not
I told you what the user error was jn
!d discord.Intents.members
It's fine haha. Didn't really had much motivation to continue that game since there were many clones, so working on a machine learning ebook API for a month now, with a friend of mine
discord.User does not have an add_role() method you'd want discord.Member for that
He can have User only in DM channel or if there are issues with intents
so i change await message.author.add_roles(role)?
Or if lib smokes grass (it sometimes does)
The same way you get the role message.guild.get_role you can just do message.guild.get_member() / fetch_member
No, please tell me, what intents do you have enabled
Ur amazing fam
huh
bot = commands.Bot(command_prefix = prefixxx, case_insensitive=True, activity=discord.Game(name="RPM", type=3))
u mean this?
Haha thanks!
Oh you have no intents
:/
!intents
Using intents in discord.py
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default discord.py has all intents enabled except for Members, Message Content, and Presences. These are needed for features such as on_member events, to get access to message content, and to get members' statuses.
To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.
Next, in your bot you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:
from discord import Intents
from discord.ext import commands
intents = Intents.default()
intents.members = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see the discord.py docs on intents, and for general information about them, see the Discord developer documentation on intents.
yh dat too
i copy this?
intents = Intents.default()
intents.members = True
and import the intents thing
huh
You'd better read everything

bot = commands.Bot(..., intents=intents)```
Members
i enabled all
Logic π€
and still got the same error
Ok then change your intents to discord.Intents.all()
Tbh it shouldn't really matter, you don't need presence for example
How do i make it have a new line?
How do i make it have a new line?
wdym?
Well you can use \n for new line, but not sure what you exactly want
lol
this was master having changes that the pr wasn't up to date with
had to merge master into the pr
you're too smart, Hunter
hunter is the smartest here
Always pull when you are going to edit code π
Indeed
btw disnake master now has perms v2 support
:(
When you got no cpu
totally not a horrible starting
3gb
Mine uses dead 69 mb of ram
How does your anti spam AI going?
cpu doesn't cross that 5% even when doing multiple img processing
Gotta stress test that though
I host bots on samovar no cap
Loving that wood floor
Cool
And it's in 27 guilds
my dev bot uses 86 mb of ram in one guild
and my public bot uses around 95mb
which is in 100 guilds
My public bot that I can't run because of stupid slash commands consumes like 300 mb
I rmr my conversion to slash commands
Lol
And I am too lazy to rewrite it rn because it was literally based on messages
Also it has many constructions that I have found a better approach to so I am feeling cringe when working with it
Thankfully I only had to remake my decorator to convert most of my commands to slash
So that saved me alot of pain
Understandable
It is always like so lol
If i'm gonna open one of my school project now probably i'd punch me so hard
Aias has perfect stuff tho I haven't found anything to improve except I might have to bring the database version control stuff out somewhere
Rn I'm tryna make a way to internally test all my commands by using a fake discord connect of sort that's gonna supply fake user info etc
It seems really pointless, but I'm bored
Ah yes that's a cool idea
Traceback (most recent call last):
File "bot.py", line 266, in <module>
client.run(TOKEN, bot=True, reconnect=True)
File "/home/runner/NugSec/venv/lib/python3.8/site-packages/discord/client.py", line 723, in run
return future.result()
File "/home/runner/NugSec/venv/lib/python3.8/site-packages/discord/client.py", line 702, in runner
await self.start(*args, **kwargs)
File "/home/runner/NugSec/venv/lib/python3.8/site-packages/discord/client.py", line 665, in start
await self.login(*args, bot=bot)
File "/home/runner/NugSec/venv/lib/python3.8/site-packages/discord/client.py", line 511, in login
await self.http.static_login(token.strip(), bot=bot)
File "/home/runner/NugSec/venv/lib/python3.8/site-packages/discord/http.py", line 300, in static_login
data = await self.request(Route('GET', '/users/@me'))
File "/home/runner/NugSec/venv/lib/python3.8/site-packages/discord/http.py", line 216, in request
raise HTTPException(r, data)
discord.errors.HTTPException: 429 Too Many Requests (error code: 0): <!DOCTYPE html>
Just got hit with this out of the blue. Been running fine for ages. No changes done.
Any thoughts on what happened? Tried resetting the token, but same result. 
assume that you want send message and embed link perms so it would be py has_guild_permissions( hikari.Permissions.SEND_MESSAGES | hikari.Permissions.EMBED_LINKS)
yeah yeah, I already figured that out, thanks a lot
π I'm just too dumb
you can refer to these, very helpful
yeah, been using those a lot lol
!d disnake.ext.commands.default_member_permissions
@disnake.ext.commands.default_member_permissions(value=0, **permissions)```
A decorator that sets default required member permissions for the command.
Unlike [`has_permissions()`](https://docs.disnake.dev/en/latest/ext/commands/api.html#disnake.ext.commands.has_permissions "disnake.ext.commands.has_permissions"), this decorator does not add any checks.
Instead, it prevents the command from being run by members without *all* required permissions,
if not overridden by moderators on a guild-specific basis.
See also the `default_member_permissions` parameter for application command decorators...
nice
I'm not using disnake anymore π
π
and, is there a way to get the total number of messages of a member in a server?
which lib
hikari, I just wanna know if that is possible or not
its not
hm ic
Technically no, but you can iterate through all the channel's history (for big guilds it's impossible).
and get ratelimited? not ideal, thanks though
It can actually get ~5000 messages per second, without getting global ratelimited cause discord.py handles the endpoint's ratelimit (I'm sure hikari handles that too).
but yeah, not ideal
Replit
Is the issue
Stat bots typically just track them, not fetch
Fetching is expensive procedure yk
well it's not like it is expensive, but fetching sends API request so they took more time
Thanks for the sarcasm
U r wrong
hm yeah, but but, downtime is an issue here, so i can't really track them
I wasn't joking π you're too uwu
lil Ash fell for ya
I- ||can't deny nor accept||
Well can i use it when am writing the cmd like this ill show you the ss
@slate swan another issue π
why does
@lightbulb.option(name="member", required=True, type=hikari.Member)
return a UserImpl object instead of a Member object
try using instance to compare if its a member or not
if its not, use guild.get_member(ctx.options.member)
oh oki, thanks a lot
why the name of that option isn't uwu
nvm i got it
We just point out names that should be uwu in ashley's code at this point
Someone needs to put their code through owofier and see if it still works
BECAUSE I DON'T WANT TO UWU PEOPLE EXCEPT HUNTER AND SARTHAK
Oh
Hostility
Sadge we aren't in the list
@cwient.swash_command(name=swash_command_wob, descwiption="rob someone's coin.")
async def wob_coin(message, victim: disnake.Membew):
if victim is none ow await coowdown_check(message) ow shuwtdown:
wetuwwn
pwayew = await uwsew.fetch(message)
if pwayew.id == victim.id:
content = "https://c.tenow.com/rhotix9uj30aaaac/pwayed-uwsewf-dj-khawed.gif"
await message.send(content=content, ephemewaw=twuwe)
wetuwwn
ewif pwayew.stowen is not none and pwayew.stowen < time_stamp:
content = f"youw've awweady stowen fwom someone today {message.auwthow.name}"
await message.send(content=content, ephemewaw=twuwe)
wetuwwn
pwayew.stowen = time_stamp + (24 * 60 * 60)
wetuwwn
what's the code you're using
Do you guys have buttons in cogs form?
time_stamp = datetime.now().timestamp()
int(datetime.now().timestamp())
from datetime import datetime
future_time = datetime.now().timestamp() + (60 * 60 * 24)
if future_time <= datetime.now().timestamp():
print("future time is now")
if you want one day in the future
also, the member.joined_at returns a datetime.datetime object, how can I subtract it from datetime.datetime.now?
i think you could use the delta thing
with the - sign
@command()
async def countdown(ctx):
start = 60
while t>0:
mins, secs = divmod(start, 60)
timer = "f{mins}:{secs}"
await ctx.send(timer)
await asyncio.sleep(1)
start-=1
you will get a timedelta object
I know that but it throws an error for some reason
datetime.utcnow() - member.joined_at and this is what im doing
still ashleying here Ashley 
it works with zoneaware timezones
ah I see
thanks a lot
oops my typos
.topic
Extension 'cogs.ticket' raised an error: ModuleNotFoundError: No module named 'discord.ui' I have installed this module and have imported it
And it shows this
you need discord.py 2.0
My old bot is now over 800 servers 
pip install -U git+https://github.com/Rapptz/discord.py
thank me later
That thing is an absolute mess in terms of code, my first python project, I'm shocked it's ran without any errors on an Amazon server for months
you just surpressed the errors, that's a different story
erm
π
intents = discord.Intents.all()
intents.members = True
prefixxx = ['rpm ', 'Rpm ', 'RPM ', 'RPm ']
bot = commands.Bot(command_prefix = prefixxx, case_insensitive=True, activity=discord.Game(name="RPM", type=3), intents=intents)
you need a member object
you can add roles only to a member,not a user
@bot.event
async def on_message(message) :
if message.channel.type == discord.ChannelType.private:
return
if message.channel.id == 970895283250675813 :
data = message.content.split(" ")
user = re.sub("\D", "", data[4])
hehehe = bot.get_user(user) or await bot.fetch_user(user)
hehehe = hehehe.id
db[f'{hehehe}cooked_pogchop'] += 42
db[f'{hehehe}voteCount'] += 1
voteCount = db[f'{hehehe}voteCount']
if voteCount < 10:
role = message.guild.get_role(971310924478705695)
elif voteCount < 18:
role = message.guild.get_role(971310601668288512)
elif voteCount < 69:
role = message.guild.get_role(971311031555072020)
elif voteCount < 100:
role = message.guild.get_role(971311323658977281)
elif voteCount < 420:
role = message.guild.get_role(971311024051486742)
elif voteCount >= 420:
role = message.guild.get_role(971311028694577162)
else:
role = message.guild.get_role(905626727005454457)
await message.author.add_roles(role)
await bot.process_commands(message)
oo
I hope this isn't in DM's
...
the comamnd was used in dms
huh
i dont have git instaled do you know how to install it
?
then how did you install dpy previously?
pip install discord.py
where do i do it
rewrite it π
only if you're hosting something good on it π
huh
member = message.guild.get_member(message.author.id)
i just need to take the userid why do i need to add so many thing ;-;
i add it inside or outside the bot.event
you need the member object to add roles, which is obvious
you replace it with hehehe = ...
huh
ok
nvm, I'll do a quick rewrite for you

i like this froggy
@bot.event
async def on_message(message) :
if message.channel.type == discord.ChannelType.private:
return
if message.channel.id == 970895283250675813 :
data = message.content.split(" ")
user = re.sub("\D", "", data[4])
user_id = message.author.id
db[f'{user_id}cooked_pogchop'] += 42
db[f'{user_id}voteCount'] += 1
voteCount = db[f'{user_id}voteCount']
if voteCount < 10:
role = message.guild.get_role(971310924478705695)
elif voteCount < 18:
role = message.guild.get_role(971310601668288512)
elif voteCount < 69:
role = message.guild.get_role(971311031555072020)
elif voteCount < 100:
role = message.guild.get_role(971311323658977281)
elif voteCount < 420:
role = message.guild.get_role(971311024051486742)
elif voteCount >= 420:
role = message.guild.get_role(971311028694577162)
else:
role = message.guild.get_role(905626727005454457)
member = message.guild.get_member(message.author.id)
await member.add_roles(role)
await bot.process_commands(message)```
also, a json isn't a db
i change it myself thanksss
everyone keep telling me this
then maybe you should start listening?
fixed
but replit doesnt have other choice
replit is a bad hosting service
check out #965291480992321536 for advice
What?
You can use sqlite3 for your database
Rather than json
Aiosqlite for this matter
self host is the best π³
pretend that you are a bot and execute users command is the best
thats self bot, thats against tos π³
u sponsor me vps then i use vps
there are better cheap alternatives
erm
now its not working at all
not even error
its a vote reward webhook btw
not a command
is it possible to run my bot commands from the terminal it's hosted on so no one can know who ran the command??
current code?
show me
and i keep thinking ur pfp is a panda
?
@bot.event
async def on_ready():
print('We have logged in as {0.user}'.format(bot))
bot.remove_command('help')
@bot.event
async def on_message(message) :
if message.channel.type == discord.ChannelType.private:
return
if message.channel.id == 970895283250675813 :
data = message.content.split(" ")
user = re.sub("\D", "", data[4])
user_id = message.author.id
db[f'{user_id}cooked_pogchop'] += 42
db[f'{user_id}voteCount'] += 1
voteCount = db[f'{user_id}voteCount']
if voteCount < 10:
role = message.guild.get_role(971310924478705695)
elif voteCount < 18:
role = message.guild.get_role(971310601668288512)
elif voteCount < 69:
role = message.guild.get_role(971311031555072020)
elif voteCount < 100:
role = message.guild.get_role(971311323658977281)
elif voteCount < 420:
role = message.guild.get_role(971311024051486742)
elif voteCount >= 420:
role = message.guild.get_role(971311028694577162)
else:
role = message.guild.get_role(905626727005454457)
member = message.guild.get_member(message.author.id)
await member.add_roles(role)
await bot.process_commands(message)
just open a private channel
@devout summit his is
ya?
HWAHHAHWAHAW
im asking if its possible to do what i want
it is
how
!d input π³
input([prompt])```
If the *prompt* argument is present, it is written to standard output without a trailing newline. The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that. When EOF is read, [`EOFError`](https://docs.python.org/3/library/exceptions.html#EOFError "EOFError") is raised. Example:
```py
>>> s = input('--> ')
--> Monty Python's Flying Circus
>>> s
"Monty Python's Flying Circus"
``` If the [`readline`](https://docs.python.org/3/library/readline.html#module-readline "readline: GNU readline support for Python. (Unix)") module was loaded, then [`input()`](https://docs.python.org/3/library/functions.html#input "input") will use it to provide elaborate line editing and history features.
Raises an [auditing event](https://docs.python.org/3/library/sys.html#auditing) `builtins.input` with argument `prompt` before reading input...
how is that going to help
i know input, but how do i make it so that it will run the bot commands
discord.py's main thread is blocking
@command.command
async def run(...):
code = input('enter: ...')
# code to run
so when i input run, that wll execute the command
no
you'd have to do !run
then use the terminal
i'm asking how to run commands from terminal, not chat
yes, and doing it all straight from the terminal is not possible
r u sure about that
please no
how would discord.py know which channel to send commands in
this will block your code
u would input the channel id
how would discord.py verify that you're an owner
if you want to run user input, use the wait_for method
that's not the point, you wouldn't be able to pass it a context object
well it was an assignment and i already submitted it so no use now
it's a discord bot, and it's being hosted on the same terminal i want to run the comands on
discord.py obviously knows i would be the owner
of the said bot
that's not how it works
oh
discord.py isn't built with this kind of functionality
you're gonna have to hack away at the entire library
it's not but, i sure hope you know how to do that
jesus why can't you just
run an eval command and delete it
code was meant to be degraded and rebuilt
and forget ctx, that wont work because it would require text on a channel
i just want to be able to run a command from terminal
you can't do it with discord.py
no
you're gonna have to send the payloads to the discord api manually
why, u said it's possible if i hack away at the library
do you not understand what that means
i do understand what it means
and i am willing to if it will acquire my sucsess in what i intend to do
from when i entered this channel
you're gonna have to learn the entire structure of this library which you know basically nothing about
then you're gonna have to find a way, god knows how, to entirely disable stdout blocking, basically getting rid of your ability to ever print anything on the terminal again
and then send requests to the discord api manually, which you're gonna have to learn how to structure
funny way of saying, "i don't know what im doing" but okay
pip install discord.py-Console
would u look at what i just found
π
whats the best way to add button interactions in discord.py
thats what i need as well lol
!d discord.ui.View
class discord.ui.View(*, timeout=180.0)```
Represents a UI view.
This object must be inherited to create a UI within Discord.
New in version 2.0.
i need discord.py 2.0 correct ?
yes
whats the process to update ? i cant find pip command
pip install -U git+https://github.com/Rapptz/discord.py
^ git must be installed
^
ok thanks
erm
help?
@bot.event
async def on_message(message) :
if message.channel.type == discord.ChannelType.private:
return
if message.channel.id == 970895283250675813 :
data = message.content.split(" ")
user = re.sub("\D", "", data[4])
user_id = message.author.id
db[f'{user_id}cooked_pogchop'] += 42
db[f'{user_id}voteCount'] += 1
voteCount = db[f'{user_id}voteCount']
if voteCount < 10:
role = message.guild.get_role(971310924478705695)
elif voteCount < 18:
role = message.guild.get_role(971310601668288512)
elif voteCount < 69:
role = message.guild.get_role(971311031555072020)
elif voteCount < 100:
role = message.guild.get_role(971311323658977281)
elif voteCount < 420:
role = message.guild.get_role(971311024051486742)
elif voteCount >= 420:
role = message.guild.get_role(971311028694577162)
else:
role = message.guild.get_role(905626727005454457)
member = message.guild.get_member(message.author.id)
await member.add_roles(role)
await bot.process_commands(message)
```not working at all ;-; not even error
Should I learn first class functions?
whats the issue now?
no error
First class functions?
yes
It's a record storing a function together with an environment
alright
imma change back to
@bot.event
async def on_message(message) :
if message.channel.type == discord.ChannelType.private:
return
if message.channel.id == 970895283250675813 :
data = message.content.split(" ")
user = re.sub("\D", "", data[4])
hehehe = bot.get_user(user) or await bot.fetch_user(user)
hehehe = hehehe.id
db[f'{hehehe}cooked_pogchop'] += 42
db[f'{hehehe}voteCount'] += 1
voteCount = db[f'{hehehe}voteCount']
if voteCount < 10:
role = message.guild.get_role(971310924478705695)
elif voteCount < 18:
role = message.guild.get_role(971310601668288512)
elif voteCount < 69:
role = message.guild.get_role(971311031555072020)
elif voteCount < 100:
role = message.guild.get_role(971311323658977281)
elif voteCount < 420:
role = message.guild.get_role(971311024051486742)
elif voteCount >= 420:
role = message.guild.get_role(971311028694577162)
else:
role = message.guild.get_role(905626727005454457)
await message.author.add_roles(role)
await bot.process_commands(message)
What
now its worse
A closure is an inner function that remembers and has access to variables in the local scope in which it was created even after the outer function has finished executing
tried debugging? -> does the on_msg even get invoked?
The hell did you search
the top.gg legit show error msg
which is?
that's your hosting service or whatever, not your actual bot
that is top.gg
its a webhook so i use the send test thing
this has nothing to do with your on_message event
Bruh you are talkin about programming terms here where 70% of people doesn't even know the difference between a method and a parameter lol
just test it like a normal dev
gg
no experience with that, I'd just send a msg in the channel to test ig
argument and parameter is still ok
...
its not a command ;-;
why is it named on_message.
Oh a decorator
what is csrf token
then where should i put it
simple as that lel
you are trying to create a trigger when someone votes right?
Just say decorator
!pip dblpy
Why make it harder for people to understand
just use this.
ok
it will add an on_dbl_vote event
Am i one of those people
ok
I don't think so
I hope you're right
what is csrf token

Cross-Site Request Forgery (CSRF) is an attack that forces authenticated users to submit a request to a Web application against which they are currently authenticated. CSRF attacks exploit the trust a Web application has in an authenticated user.
basically the token you get from that site
time to make one for hikari
i have given so much data to google, the search optimization is 
On_msg is an eventβ¦
:/
File "c:\Users\thoma\OneDrive\Desktop\discord server bot\Bot2.py", line 8, in <module>
from discord_components import DiscordComponents
File "C:\Users\thoma\AppData\Local\Programs\Python\Python310\lib\site-packages\discord_components\__init__.py", line 1, in <module>
from .client import *
File "C:\Users\thoma\AppData\Local\Programs\Python\Python310\lib\site-packages\discord_components\client.py", line 12, in <module>
from .component import Component
File "C:\Users\thoma\AppData\Local\Programs\Python\Python310\lib\site-packages\discord_components\component.py", line 3, in <module>
from discord import PartialEmoji, Emoji, InvalidArgument
ImportError: cannot import name 'InvalidArgument' from 'discord' (C:\Users\thoma\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\__init__.py)``` Whats next?
Cat

my bot is online but its not responding to any cmnd and there is no error in console how can i fix this ??
Try and print it and see what happens
after installing dpy 2.0 all this problems started
Do u not have anything in on_ready event?
it does print think
Think..? I recommend u to confirm rather than assuming
not printing it on paper lol
Lmfao
ik
yes
you need message_content intents
@bot.event
async def on_ready():
await bot.change_presence(activity=discord.Streaming(name='Sea of Thieves',
url='https://www.twitch.tv/'))
#print('Connected to bot: {}'.format(bot.user.name))
#print('Bot ID: {}'.format(bot.user.id))
print("Bot is Online")
in dpy 2.0 intents must be turn on ?
File "c:\Users\thoma\OneDrive\Desktop\discord server bot\Bot2.py", line 8, in <module>
from discord_components import DiscordComponents
File "C:\Users\thoma\AppData\Local\Programs\Python\Python310\lib\site-packages\discord_components\__init__.py", line 1, in <module>
from .client import *
File "C:\Users\thoma\AppData\Local\Programs\Python\Python310\lib\site-packages\discord_components\client.py", line 12, in <module>
from .component import Component
File "C:\Users\thoma\AppData\Local\Programs\Python\Python310\lib\site-packages\discord_components\component.py", line 3, in <module>
from discord import PartialEmoji, Emoji, InvalidArgument
ImportError: cannot import name 'InvalidArgument' from 'discord' (C:\Users\thoma\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\__init__.py)```
What's next?
So
i mean it should give him a intent error
u mean like this ?
@bot.event
async def on_ready():
print("Bot is Online")
await bot.change_presence(activity=discord.Streaming(name='Sea of Thieves',
url='https://www.twitch.tv/'))
it still dosent wrk
Yes
DId you close the code and reopened?
i restarted
did you import the right module?
show your import
wht all r required ?
.
Eh... I don't think order "really" matters.. it should just print something
copy paste your import modules?
....
What should i do for my code error?
File "c:\Users\thoma\OneDrive\Desktop\discord server bot\Bot2.py", line 8, in <module>
from discord_components import DiscordComponents
File "C:\Users\thoma\AppData\Local\Programs\Python\Python310\lib\site-packages\discord_components\__init__.py", line 1, in <module>
from .client import *
File "C:\Users\thoma\AppData\Local\Programs\Python\Python310\lib\site-packages\discord_components\client.py", line 12, in <module>
from .component import Component
File "C:\Users\thoma\AppData\Local\Programs\Python\Python310\lib\site-packages\discord_components\component.py", line 3, in <module>
from discord import PartialEmoji, Emoji, InvalidArgument
ImportError: cannot import name 'InvalidArgument' from 'discord' (C:\Users\thoma\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\__init__.py)```
i know
but it has nothing to do with intent but yes i have enabled in developer and in code
where can i paste my code to show ?
!paste @stiff gorge
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.
Well i think it means that from discord import PartialEmoji, Emoji, InvalidArgument~i need to import this modules =but it still wont work
make sure to do the intents like this intents = discord.Intents.default() intents.members = True
client = commands.Bot(command_prefix = '!', intents = intents)
after doing this i get a error
Traceback (most recent call last):
File "/home/runner/mv/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 924, in _load_from_module_spec
await setup(self)
File "/home/runner/mv/cogs/help.py", line 76, in setup
await bot.add_cog(Help(bot))
File "/home/runner/mv/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 760, in add_cog
cog = await cog._inject(self, override=override, guild=guild, guilds=guilds)
File "/home/runner/mv/venv/lib/python3.8/site-packages/discord/ext/commands/cog.py", line 563, in _inject
raise e
File "/home/runner/mv/venv/lib/python3.8/site-packages/discord/ext/commands/cog.py", line 557, in _inject
bot.add_command(command)
File "/home/runner/mv/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 226, in add_command
super().add_command(command)
File "/home/runner/mv/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 1262, in add_command
raise CommandRegistrationError(command.name)
discord.ext.commands.errors.CommandRegistrationError: The command help is already an existing command or alias.
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "main.py", line 133, in <module>
asyncio.run(main())
File "/nix/store/p21fdyxqb3yqflpim7g8s1mymgpnqiv7-python3-3.8.12/lib/python3.8/asyncio/runners.py", line 44, in run
return loop.run_until_complete(main)
File "/nix/store/p21fdyxqb3yqflpim7g8s1mymgpnqiv7-python3-3.8.12/lib/python3.8/asyncio/base_events.py", line 616, in run_until_complete
return future.result()
File "main.py", line 121, in main
await bot.load_extension('cogs.help')
File "/home/runner/mv/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 990, in load_extension
await self._load_from_module_spec(spec, name)
File "/home/runner/mv/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 929, in _load_from_module_spec
raise errors.ExtensionFailed(key, e) from e
discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.help' raised an error: CommandRegistrationError: The command help is already an existing command or alias.
i just upgraded to dpy 2.0 and the bot doesnt respond to any command now. i went through the breaking changes and i dont see anything that should cause that.
Well it says it right there dude The command help is already an existing command or alias.
there is no 2 cmnd
i checked the cogs name is help and the cmnd name is help
is this the reason ?
Well i think it means that
from discord import PartialEmoji, Emoji, InvalidArgument
~i need to import this modules =but it still wont work
Try and maybe change the name
what does this mean ?
and then restart the code
ok
are you in the changelogs?
its a kwarg used while selfbotting in 1.7.3...
it says the error is here in the middle line
async def setup(bot):
await bot.add_cog(hlpcmnd(bot))
print("Added Helpcmnd cog")
hmmm i am not sure why the bot will not respond to commands now although its running with any error
You're making your own custom help command?
message_content intents.
make sure that the class cog are named the same
its group cmnd
yes it is
anyone mind checking #help-donut
its sleeping
is this the problem ?
@commands.group(name='help',invoke_without_command=True)
@commands.cooldown(1, 5, commands.BucketType.user)
async def help(self, ctx):
embed0 = discord.Embed(title='__HELP COMMAND__',
description=f'Type `{prefix}help <page>` To get help about specific command',color=0xFFDF00)
embed0.add_field(name='Page 1',
value='```Fun Commands```\n')
embed0.add_field(name='Page 2',
value='```Image Commands```\n')
embed0.add_field(name='Page 3',
value='```Information Commands```\n')
embed0.add_field(name='Page 4',
value='```Rank Commands```\n')
embed0.add_field(name='Page 5',
value='```Economy Commands```\n')
embed0.add_field(name='Page 6',
value='```Bot Infrmation```\n')
embed0.set_footer(text='Page (0/1)')
await ctx.send(embed=embed0)
this is the first help cmnd
@help.command(name='1',aliases=['Information','information','info'])
async def pg_one(self, ctx):
embed = discord.Embed(color=0x2f3136)
embed.add_field(name=f'**:Information:γ»Information Commands ** ',value= "\n **` 1 ` Fact** - Its just a fact bro.""\n"
"**` 2 ` Joke** - See some funny jokes.""\n" "**` 3 ` Weather** - To confine someone to a coffin.""\n"
"**` 4 ` Insult** - Delivers a insulting message.",inline=False)
embed.set_footer(text='Page (1/8)')
await ctx.send(embed=embed)
this is the last one
so ```py
Traceback (most recent call last):
File "/pufferpanel/.local/lib/python3.10/site-packages/disnake/client.py", line 531, in _run_event
await coro(*args, **kwargs)
File "/pufferpanel/.local/lib/python3.10/site-packages/disnake/ext/commands/interaction_bot_base.py", line 1343, in on_application_command_autocomplete
await self.process_app_command_autocompletion(interaction)
File "/pufferpanel/.local/lib/python3.10/site-packages/disnake/ext/commands/interaction_bot_base.py", line 1261, in process_app_command_autocompletion
await slash_command._call_relevant_autocompleter(inter)
File "/pufferpanel/.local/lib/python3.10/site-packages/disnake/ext/commands/slash_core.py", line 549, in call_relevant_autocompleter
await inter.response.autocomplete(choices=choices)
File "/pufferpanel/.local/lib/python3.10/site-packages/disnake/interactions/base.py", line 1051, in autocomplete
await adapter.create_interaction_response(
File "/pufferpanel/.local/lib/python3.10/site-packages/disnake/webhook/async.py", line 216, in request
raise HTTPException(response, data)
disnake.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In data.choices.6.name: This field is required
This is error and code is ```py
@build.autocomplete("gun")
async def build_autocomplete(self, inter, option) -> typing.List[str]:
_all = await get_weapons(inter)
if option in _all:
return [option]
matches = fuzzy_match(option, _all, n=10)
return [match for match in matches if match]
File "c:\Users\thoma\OneDrive\Desktop\discord server bot\Bot2.py", line 8, in <module>
from discord_components import DiscordComponents
File "C:\Users\thoma\AppData\Local\Programs\Python\Python310\lib\site-packages\discord_components\__init__.py", line 1, in <module>
from .client import *
File "C:\Users\thoma\AppData\Local\Programs\Python\Python310\lib\site-packages\discord_components\client.py", line 12, in <module>
from .component import Component
File "C:\Users\thoma\AppData\Local\Programs\Python\Python310\lib\site-packages\discord_components\component.py", line 3, in <module>
from discord import PartialEmoji, Emoji, InvalidArgument
ImportError: cannot import name 'InvalidArgument' from 'discord' (C:\Users\thoma\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\__init__.py)``` How do i fix this?
Reinstall
ReInstall what?
Dpy
hunter would you have an idea?
the annoying part is that it's not ignoring the error with ```py
@commands.Cog.listener()
async def on_slash_command_error(self, inter, error):
if isinstance(error, disnake.HTTPException):
return
else:
print(error)
Whats the installation module for discord ui?
Try asking in disnake
ohh thanks completely missed that
was trying since yesterday lol
maybe it's coming from here? ```py
_all = await get_weapons(inter)
if option in _all:
return [opti
now again my bot has cm online but not responding
what is dbl in full
hm?
File "c:\Users\thoma\OneDrive\Desktop\discord server bot\cogs\ticket.py", line 3, in <module>
from discord.ui import Button, View
ModuleNotFoundError: No module named 'discord.ui'```
^
Probably because of no proper typehints
ur embed is kinda weird
You can try typehinting channel: discord.TextChannel = ... also you don't need description kwarg in your embed as it's empty
didnt used to get warning in dpy 1.7....after ugrading to 2.0 getting it.
ok
And yeah get the channel by its id for god's sake this is not the case for utils.get
discord bot list..
3rd time, message_content intents
LOL
Try "unwrapping" the error
error = getattr(error, "original", error)```
class TopGG(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.token = 'dbl_token' # set this to your DBL token
self.dblpy = dbl.DBLClient(self.bot, self.token, webhook_path='/dblwebhook', webhook_auth='password', webhook_port=5000)
@commands.Cog.listener()
async def on_dbl_vote(self, data):
if message.channel.type == discord.ChannelType.private:
return
if message.channel.id == 970895283250675813:
data = message.content.split(" ")
user = re.sub("\D", "", data[4])
hehehe = bot.get_user(user) or await bot.fetch_user(user)
hehehe = hehehe.id
db[f'{hehehe}cooked_pogchop'] += 42
db[f'{hehehe}voteCount'] += 1
voteCount = db[f'{hehehe}voteCount']
if voteCount < 10:
role = message.guild.get_role(971310924478705695)
elif voteCount < 18:
role = message.guild.get_role(971310601668288512)
elif voteCount < 69:
role = message.guild.get_role(971311031555072020)
elif voteCount < 100:
role = message.guild.get_role(971311323658977281)
elif voteCount < 420:
role = message.guild.get_role(971311024051486742)
elif voteCount >= 420:
role = message.guild.get_role(971311028694577162)
else:
role = message.guild.get_role(905626727005454457)
await message.author.add_roles(role)
await bot.process_commands(message)
```am i doing this correctly?
tias
?
use the on_dbl_test event
huh
try it and see
?
I'd just do raw requests π
tbh i don't think it'll change anything
Who needs those libs
isn't that mostly for commandinvoke errors?
can i make message a parameter?
!intents
cuz message is undefined
Using intents in discord.py
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default discord.py has all intents enabled except for Members, Message Content, and Presences. These are needed for features such as on_member events, to get access to message content, and to get members' statuses.
To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.
Next, in your bot you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:
from discord import Intents
from discord.ext import commands
intents = Intents.default()
intents.members = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see the discord.py docs on intents, and for general information about them, see the Discord developer documentation on intents.
doing ctx.channel.send() solved it
You should try anyway. Also have you printed the type of exception?
no why π
;-;
i tried replicating the code to my test bot and i'm not getting the error
how is a voting event related to a message??
he vote i got a msg and give him a reward
With unwrapping?
use get_user to get your user and use User.send to send the message to urself
So you are not getting it even in the handler?
its here already
Hello any one
Hi
yeah not in terminak
terminal
it is enabled but still bots not responding
show where you enabled it
@spring flax try to print the type of received exception and see what it says
how?
print(type(error))```
where do you want me to do that?
In your handler
i dont think HTTPExceptions like missing permissions can be traced using error handler
Depends where they occur
Any exception from the command gets wrapped into CommandInvokeError (or whatever it's named idr) and goes to the error handler
import os
import json
import asyncio
import discord
import platform
import keep_alive
from discord import Intents
from datetime import datetime
from discord.ext import commands
print("Discord Version:",discord.__version__)
print("Python Version:", platform.python_version())
from discord.ext import tasks ,commands
intents = discord.Intents.default()
intents.members = True
Totally enabled
Lmfao
bot = commands.Bot(command_prefix = 'm!', intents=intents)
Still totally enabled
You only enabled members intent
You need messages content intent as well
Not message_content and messages
i said message_content intents, not members
#coin
@commands.command()
async def coin(self, ctx):
responses=["Heads", "Tails"]
responses=random.choice(responses)
emb=discord.Embed(title="Coin Toss", description=":coinnn:flipping a coin...", colour=discord.Color.gold())
emb.set_thumbnail(url="https://cdn.discordapp.com/attachments/960489755114622988/971313164681609266/1651647646817.png")
emb.add_field(name="Answer:", value=f"`{responses}`")
await ctx.reply(embed=emb)```
url invalid?
no
Exe how'd you get that much data to train your model
invalid link.
the message with this image got deleted
hm
thx
First I just made it put all the messages to the database and then I went to mark them as spam/not spam one by one by myself
What the fuck
Currently there are almost 12k samples, 4,5k validated and only 150 of them are spam
How'd you label them as spam?
Well how do you label a message as spam
When there's multiple messages of the same thing
In a short period of time
But how are you labeling each message as spam
utils/processors/messages.py lines 59 to 64
queue = self.add(message)
if queue == False:
return False
full_content = " ".join([m.content for m in queue])
if is_spam(full_content):```
looking through the source, disnake doesnt dispatch any error handlers for autocomplete just like discord.py
but to fix the missing name field in your choice id suggest printing the list in your autocomplete for anything out of place, e.g. strings that only have whitespace
Oh
so can I handle those?
afaik no, which seems kind of weird
no I mean not with an error handler, just anything to stop the error
well try what i said, print the list and look for strings that discord wouldnt accept
so I'm trying to repro the error on my test bot and it's not coming up, not sure why it's coming in the first place
Read the select menu examples on the repository
!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").
autosend as in sending the message every once in a while, right?
you'd need something like
from discord.ext import tasks
@tasks.loop(hours=...)
async def auto_send():
channel = Bot.get_channel(...)
await channel.send(...)
How to display a list of servers on which a people is an administrator, as in JuniperBot or MEE6
.........
No copypasting π π
Just figure it out
You decorate a function and turn it into the Loop and then you start the loop
VSC live share
nvm
Best thing
Pycharm also has stuff like that
Github has their "shared workspaces" but they are not free afaik
Open visual studio code and search "live share" in extensions
Its interface is intuitively figureable
He needs that extension too
Or he can join from browser but it's cringe imo
@bot.command(name='ac', help='commands prefix')
async def asdasdsd(ctx):
button = Button(label="click me!",style=discord.ButtonStyle.success)
view = View()
view.add_item(button)
await ctx.send("hi",view=view)
i am getting this
It has no callback
Look at the components examples in the library repo
You should subclass views or create some classes for easier management
There should be its tab and a button "start collaboration session" or smth
Did you restart the vsc
ok thnks got it
bruh
help_command = None
you ok?
no π no datetime is giving me a stroke
Strings conversion?
calculation of time period, like I wanna get the time when the user joined the guild and was removed, But there's just a lot of errors trying to get that timespan
Just datetime.now() - user.joined_at?
show code
just a min
did you use .joined_at.astimezone()?
No
yeah I did
same error?
idk, it should be returning just hours, its returning days and stuff, i'll get the code and ouput in a sec
alright
_join_date = member.joined_at
delta = timedelta(hours=0)
Timezone = timezone(delta, "UTC")
join = _join_date.astimezone(Timezone)
join_span = (datetime.utcnow().astimezone(Timezone) - join)
output - 70 days, 0:39:03.046215
..
idk if I'm using astimezone the wrong way
the days is correct right?
wait wait wait
i think i figured it out
thanks uwu
πΆββοΈ me who uses timestamps
100 iq
the timestamp style is R
um how do I add like x days ago and all
yeah its relative, I saw, I'll test that
Me who uses sundials
but wait, I dont want timestamps, I want the amount of time in the server
Are there more?
!e py print(f"<t:{int(__import__('datetime').datetime.now().timestamp())}:R>
i think?
async def afkcheck(ctx) -> bool:
async with ctx.bot.afkdb.cursor() as cursor:
await cursor.execute('SELECT role FROM afkrole WHERE guild = ?', (ctx.guild.id,))
data = await cursor.fetchone()
if data:
if data[0] in ctx.author.roles:
return True
else:
return False
else:
return True
await ctx.bot.afkdb.commit()
returned false even when i took the required role
relative
you can make a timestamp of the joined_at with R type and it would be the same
oh
Thanks
you saved the role id, not the role object didnt you
hm i see
in database, yes
oh gotcha
so you need to get the role first then use in
Okay
sparky never fails to make me feel like im talking to myself
.lol