#discord-bots
1 messages Β· Page 796 of 1
No no, know where the issue is
typecast channel to discord.TextChannel
then you can store the ID
perfect
you got it
sure
this gets a channel from the cache, not the database
ah
since your "database" is a json, if you use the json library, it will parse the file into a python dict object
so how do i get the id?
x = json.load(json_file)
x['key'] # List of channels
(that's only psuedocode)
in your case 'key' would be the part in blue
guild id
i assume that's a guild ID?
ye ye
so guild ID is a list of channel ids?
basically the guild id is set in a dict
and even tho im creating a list
im trying to add just 1 channel per each guild id
why? why not just guild-channel pair?
{
"guildID": "channelID",
"12345": "67890"
}
each key is a guildID, each value is that guild's channel ID
that would be way better
but how π
i mean i can use this way
and just check if there's already a channel
well whenever you add an entry to the json, just add a single channel to a single guild ID
rather than a list of a single channel ID to a single guild ID
π€ why?
idk i feel like it's easier
quite inefficient and makes it more complicated don't you think
i'll be honest
this feels more easier π
i probably need more help adding that
and i don't want to make u lose braincells
well yeah using json as a db is never a good idea in the first place
nah it's alright, seen worse haha
i use sql for other things
my bad π
could have this part of your sql database as well
won't harm to have another table
is it?
yep
i mean it works perfectly fine
sure but it's still blocking
mmm
it can take down your bot easily if it blocks at the right time and your client doesn't send a heartbeat
not to mention it's slower and blocks the entire event loop
https://github.com/an-dyy/Rin/blob/a836b975ed8ab0981014ca57bc8fcef729d61756/examples/example_collector.py#L1-L28 what do you guys think ποΈ ποΈ
the section at the bottom of my code is preventing the bot from sending messages, anyway to implement that section and other commands? https://github.com/zoaq1/Meno-Discord-Bot/blob/main/main.py
Aw it didn't code-block it
Guess it is to big π
on_message
you need process_command()
and because i don't want to use channel as a required parameter i am trying to get the id from json
can u explain to me one more time?
i still didn't get it
i need process_command() where it says on_message?
that way you can just get it from json, then int() it
oh bruh
it still adds as <#>
wha-
im using channel.id tho
why is it adding with <#>
yea
all the way at the end, yes
@antichannel.command()
@commands.check_any(commands.is_owner(), is_guild_owner())
async def add(self, ctx, channel: discord.TextChannel):
with open(prefix_path, "r")as f:
prefixes = json.load(f)
prefixes[str(ctx.guild.id)]
p = prefixes.get(str(ctx.guild.id))
with open(channel_path, "r") as f:
add_channel = json.load(f)
if not str(ctx.guild.id) in add_channel:
em = discord.Embed(title=" Antinuke Error!", description=f"Turn on the antinuke logs first!", color=discord.Color.red())
await ctx.reply(embed=em, mention_author=False)
return
if len(add_channel[str(ctx.guild.id)]) == 1:
em = discord.Embed(title=" Antinuke Error!", description=f"{channel.mention} Is currently set for the antinuke logs!\nType: `{p}Antichannel Remove` To remove the channel!", color=discord.Color.red())
await ctx.send(embed=em)
return
if str(channel.id) not in add_channel[str(ctx.guild.id)]:
add_channel[str(ctx.guild.id)].append(str(channel.id))
else:
em = discord.Embed(title=" Antinuke Error!", description=f"{channel.mention} Is already set as the current channel!", color=discord.Color.red())
await ctx.reply(embed=em, mention_author=False)
return
with open(channel_path, "w") as f:
json.dump(add_channel, f, indent=4)
em = discord.Embed(title=" Antinuke Successful!", description=f"{channel.mention} Has been added set for the antinuke logs!", color=discord.Color.from_rgb(black1, black2, black3))
await ctx.reply(embed=em, mention_author=False)
@add.error
async def channel_error(self, ctx, error):
if isinstance(error, commands.MissingRequiredArgument):
em = discord.Embed(title=" Antinuke Error!", description="Please provide a channel [`Mention/ID`]!", color=discord.Color.red())
await ctx.reply(embed=em, mention_author=False)
elif isinstance(error, CommandError):
em = discord.Embed(title=" Antinuke Error!", description="Only the owner can perform this action!", color=discord.Color.red())
await ctx.reply(embed=em, mention_author=False)
this is how the code looks like
on_message gets called before your command handlers so it's possible for user inputs to not get passed to the command handler
yeah
but still why is it adding as <#>
π€
now the commands work but no the autodelete
should i try to print it?
yes please
imma print channel and channel id
channel.id
make sure you add it at the very end of the on_message
make sure it's inside, not outside
like this?
@client.event
async def process_command(message):```
No, it's just a coro
You don't have to define it yourself
async def on_message(...):
...
await bot.process_commands(...)
yo
You can also just use client.listen()
alternatively, inside a cog:
@commands.Cog.listener()
async def on_message(...):
...
# no need for process_commands()
this would also work outside of a cog, no need for process_commands()
that's odd, it made a new entry with <#>?
yep
@antichannel.command()
@commands.check_any(commands.is_owner(), is_guild_owner())
async def add(self, ctx, channel: discord.TextChannel):
with open(prefix_path, "r")as f:
prefixes = json.load(f)
prefixes[str(ctx.guild.id)]
p = prefixes.get(str(ctx.guild.id))
with open(channel_path, "r") as f:
add_channel = json.load(f)
if not str(ctx.guild.id) in add_channel:
em = discord.Embed(title=" Antinuke Error!", description=f"Turn on the antinuke logs first!", color=discord.Color.red())
await ctx.reply(embed=em, mention_author=False)
return
if len(add_channel[str(ctx.guild.id)]) == 1:
em = discord.Embed(title=" Antinuke Error!", description=f"{channel.mention} Is currently set for the antinuke logs!\nType: `{p}Antichannel Remove` To remove the channel!", color=discord.Color.red())
await ctx.send(embed=em)
return
if str(channel.id) not in add_channel[str(ctx.guild.id)]:
add_channel[str(ctx.guild.id)].append(str(channel.id))
print(f"{channel} This is channel")
print(f"{channel.id} This is channel id")
else:
em = discord.Embed(title=" Antinuke Error!", description=f"{channel.mention} Is already set as the current channel!", color=discord.Color.red())
await ctx.reply(embed=em, mention_author=False)
return
with open(channel_path, "w") as f:
json.dump(add_channel, f, indent=4)
em = discord.Embed(title=" Antinuke Successful!", description=f"{channel.mention} Has been added set for the antinuke logs!", color=discord.Color.from_rgb(black1, black2, black3))
await ctx.reply(embed=em, mention_author=False)
it creates it with <#> automatically
that's not right π€
and you're sure you deleted everything inside the .json before trying this?
yep
definitely not right
do you have an external function doing it?
sometimes people make helper functions and forget they still have it
lemme check again
actually instead of removing everything, just remove the "<#IDHERE>", so it looks like
{
"guildID": []
}
then try it
great
but
it wont remove
@antichannel.command()
@commands.check_any(commands.is_owner(), is_guild_owner())
async def remove(self, ctx):
with open(prefix_path, "r")as f:
prefixes = json.load(f)
prefixes[str(ctx.guild.id)]
p = prefixes.get(str(ctx.guild.id))
with open(channel_path, "r") as f:
remove_channel = json.load(f)
remove_channel[str(ctx.guild.id)]
channel = remove_channel[str(ctx.guild.id)]
if not str(ctx.guild.id) in remove_channel:
em = discord.Embed(title=" Antinuke Error!", description=f"The antinuke logs are not enabled!", color=discord.Color.red())
await ctx.reply(embed=em, mention_author=False)
return
try:
if str(channel) in remove_channel[str(ctx.guild.id)]:
remove_channel[str(ctx.guild.id)].remove(str(channel))
em = discord.Embed(title=" Antinuke Successful!", description=f"{channel.mention} Has been removed from the antinuke logs!\nType: `{p}Antichannel Add [Mention/ID]` To add a channel!", color=discord.Color.from_rgb(black1, black2, black3))
await ctx.reply(embed=em, mention_author=False)
with open(channel_path, 'w') as f:
json.dump(remove_channel,f)
except:
em = discord.Embed(title=" Antinuke Error!", description=f"No channel was found in the database!\nType: `{p}Antichannel Add [Mention/ID]` To add a channel!", color=discord.Color.red())
await ctx.send(embed=em)
@remove.error
async def channel_error(self, ctx, error):
if isinstance(error, CommandError):
em = discord.Embed(title=" Antinuke Error!", description="Only the owner can perform this action!", color=discord.Color.red())
await ctx.reply(embed=em, mention_author=False)
let's see
wym
well accessing dicts returns a value
what's the point of accessing without storing it in a variable
remove_channel[str(ctx.guild.id)]
channel = remove_channel[str(ctx.guild.id)]
this part
the first line there doesn't do anything
huh
oh yea
my bad
deleted it
@antichannel.command()
@commands.check_any(commands.is_owner(), is_guild_owner())
async def remove(self, ctx):
with open(prefix_path, "r")as f:
prefixes = json.load(f)
prefixes[str(ctx.guild.id)]
p = prefixes.get(str(ctx.guild.id))
with open(channel_path, "r") as f:
remove_channel = json.load(f)
channel = remove_channel[str(ctx.guild.id)]
if not str(ctx.guild.id) in remove_channel:
em = discord.Embed(title=" Antinuke Error!", description=f"The antinuke logs are not enabled!", color=discord.Color.red())
await ctx.reply(embed=em, mention_author=False)
return
try:
if str(channel) in remove_channel[str(ctx.guild.id)]:
remove_channel[str(ctx.guild.id)].remove(str(channel))
em = discord.Embed(title=" Antinuke Successful!", description=f"{channel.mention} Has been removed from the antinuke logs!\nType: `{p}Antichannel Add [Mention/ID]` To add a channel!", color=discord.Color.from_rgb(black1, black2, black3))
await ctx.reply(embed=em, mention_author=False)
with open(channel_path, 'w') as f:
json.dump(remove_channel,f)
except:
em = discord.Embed(title=" Antinuke Error!", description=f"No channel was found in the database!\nType: `{p}Antichannel Add [Mention/ID]` To add a channel!", color=discord.Color.red())
await ctx.send(embed=em)
alright let's see now

i dont think so
oh wait yes it is
nope
str(channel) will remove channel's name
so right now it looks in the list, and tries to remove an entry with the channel's name
yep
your try/except catches all errors
try to either print the error or narrow down the error
imma remove the try and except so we can see
or even better, dict.get() will return None if not found rather than throw a KeyError
!e
myDict = {
"x": "test1",
"y": "test2",
}
print(myDict.get("x"))
print(myDict.get("does not exist"))
@sick birch :white_check_mark: Your eval job has completed with return code 0.
001 | test1
002 | None
i gotta get the object from inside the list
why? just remove the ID
no, it's already an ID in the json
0 is the first
then wtf
and your list will only have 1 element
You could you use hexadecimal values for colours, less code and achieves the same effect
it's fine
maybe it tried to get the first element before there was even an element
this is the problem with lists, they act kind of weird
fr
worked but
it's weird cuz
i tried pinging the channel
instead of using channel
do u know why?
make sure the list actually has something inside it before accessing it
Would a cooldown work on a on_message command?
there is
You would have to implement it yourself
@commands.Cog.listener()
@commands.cooldown(1, 300, commands.BucketType.user)
async def on_message(self, message):
I thought this would work
It wont
Just create commands like a normal person
considering this on message is for dms
for information from the modmail
isnt an actual command
this is an event not an @commands.command()
I know...
@sick birch
look
if str(channel[0]) in remove_channel[str(ctx.guild.id)]:
remove_channel[str(ctx.guild.id)].remove(str(channel[0]))
em = discord.Embed(title=" Antinuke Successful!", description=f"<#{str(channel[0])}> has been removed from the antinuke logs!\nType: `{p}Antichannel Add [Mention/ID]` To add a channel!", color=discord.Color.from_rgb(black1, black2, black3))
await ctx.reply(embed=em, mention_author=False)
with open(channel_path, 'w') as f:
json.dump(remove_channel,f)
make sure the list is filled up before you send that message
it's doing that because the list is empty
(or use guildID <-> channel ID pairs instead of a list)
!d discord.ui.View.remove_item
remove_item(item)```
Removes an item from the view.
Β―_(γ)_/Β―
Consider just disabling the buttons instead of removing them
i can't bruh how
str(channel[0])[str(ctx.guild.id)] smth like this?
imma just use channel
literally the word channel
ok
Guys I am using discord.py for rich presence but on mobile its ok, but in pc, it shows like playing since 19k days
I have a question, is there a way that a task or something similar can be run at a specific datetime?
how would i define member here
import member
right now it doesnt know what class your talking about
like so?
how would i do it then
from discord import Member
it shows up now
nice
without doing what you said above
show your imports
the heck
most of it was for an auto type to troll a friend
πͺπΆ
well shit
i cant help anymore to much errorsπ
Imports should be grouped in the following order:
standard library imports
related third party imports
local application/library specific imports
i just import by groups
Well fix
Traceback (most recent call last):
File "C:\Users\E\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\ext\commands\bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\E\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\ext\commands\core.py", line 855, in invoke
await self.prepare(ctx)
File "C:\Users\E\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\ext\commands\core.py", line 789, in prepare
await self._parse_arguments(ctx)
File "C:\Users\E\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\ext\commands\core.py", line 697, in _parse_arguments
transformed = await self.transform(ctx, param)
File "C:\Users\E\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\ext\commands\core.py", line 542, in transform
raise MissingRequiredArgument(param)
discord.ext.commands.errors.MissingRequiredArgument: ctx is a required argument that is missing.
the traceback is what i get
You shouldn't have self
You're not in a class
no like groups by category
wdym
from discord.ext import commands
from discord import Member
import random
import asyncio
etc
Also, for your project do you care if I make pull requests for tiny pep8 violations
Well it's technically wrong
go ahead
ik
def get_tweet(self, tweet_id: int) -> dict[Any, Any]:
try:
self.cache[tweet_id]
except KeyError:
raise "No such tweet"
Why type hint if you're not returning anything
import random, asyncio
from discord import Member
from discord.ext import commands
Not pep8 just wondering
oh yeah i got to fix that i forgot i deleted the return
π
imports should technically be on different lines
i just want help
so delete self
Yes
thats it
ik, it was about the import order :p
I'm literally the pep8 police
you dont even follow pep 8
We don't talk about that
not accsessed
I follow all of it except the line character limit
pain
and bare expects prob
Nope
cap
I don't do bare exceptions

halp

!d discord.ext.commands.Bot.cogs
property cogs: Mapping[str, discord.ext.commands.cog.Cog]```
A read-only mapping of cog name to cog.
returns a list, use len on it
do i delete self here too?
is it in a class?
pardon?
is it in a cog or class?
not a cog
then no need
people make mistakes, thats why we have erasers
he has a point
I guess not
no
its jus that ive seen people get the wrong id or the wrong ping tryna ban
so i delete
yes
like so?
Traceback (most recent call last):
File "C:\Users\E\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\ext\commands\bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\E\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\ext\commands\core.py", line 855, in invoke
await self.prepare(ctx)
File "C:\Users\E\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\ext\commands\core.py", line 789, in prepare
await self._parse_arguments(ctx)
File "C:\Users\E\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\ext\commands\core.py", line 697, in _parse_arguments
transformed = await self.transform(ctx, param)
File "C:\Users\E\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\ext\commands\core.py", line 542, in transform
raise MissingRequiredArgument(param)
discord.ext.commands.errors.MissingRequiredArgument: member is a required argument that is missing.
again π
well youre missing member?
do you not know your own code bruh
you need to give it a member
while invoking the command
they are not in a cog but you still use self , bet
@slate swan 
!e
def function(member: str) -> str:
return member
function()
@slate swan :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 3, in <module>
003 | TypeError: function() missing 1 required positional argument: 'member'
ironic
π
heh
I follow all of pep8 except for character limit
oki, just use black to format your code 
Fuck character limit
no

yes
no
never
you're not a dog anymore
noone likes scrolling sideways
nope
how could you do this
Too bad
and it looks ugly too
I can't do anything about it. My embed descriptions are really that long
multiline strings
use docstrings as a string :p
^^
Those look ugly as hell
if my descriptions are long I usually just make a variable with multi line strings lol
better than 100 characters long single line string
can i ask a quick question? one of my bot commands was working and is now no longer working and i cant see anything thats changed with it. even undoing any possible changes
I will 100% make my files comply with pep8
I thought Krypton was typing lol
i fixed all my imports yesterday 
Hello! I am trying to hide cogs on my code from my help commands
i tried adding command_attrs=dict(hidden=True) to my code. Now the commands dont show up but the cog still does show up. Is there anyway to hide it?
do you have an on_message event?
!d discord.ext.commands.Bot.listen
im guessing im missing something small
@listen(name=None)```
A decorator that registers another function as an external event listener. Basically this allows you to listen to multiple events from different places e.g. such as [`on_ready()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_ready "discord.on_ready")
The functions being listened to must be a [coroutine](https://docs.python.org/3/library/asyncio-task.html#coroutine "(in Python v3.9)").
Example...
use this
Where is cat pfp ποΈ ποΈ
use listen
oh Andy has a cat pfp too, nice
It's brandons cat!
Oh damn. I have too instances of my bot running. What do I do?
i can explainπ
close one of them lol
k hold up. i just got like 2-3 different answers there. one at a time
None of them are open
shut down your computer
kill one of the task, or reset your token lol
Task kill it, you can also change your token making them no longer work
bro wut
how am i trolling
i recommended a listener 
no, listen is a way to fix it too
I always reset my token but I was wondering if there was something less annoying
you can use bot.listen or process the commands, but only do one of them lol
Task killing it
Okimii did you see that new example I pushed to the repo
ik sarthak is handsom but give me a breakπ₯²
ok, so use a listener right?
yes
which collectors?
Yea the collectors one where I show off some anti-raid capabilities
Pretty cool right
let me check it out
wow thats actually really clean
π§
jeez thats cool, would help a lot with cooldowns and other stuff
why rin is gonna clap all api wrappers
ok, using the listener. would that replace the @ client.event, async def on_message(message): or await message.channel.send(response)?
cooldowns
you change the decorator
need them now
π
ok, i figured that was the case, and the name portion within it would be the text it is specifically listening for?
@bot.event will change to @bot.listen('on_message') and you can name the function whatever you want, but i think it also works if you just do @bot.listen() and keep the function name on_message
no need for it if the function is named the event
if you do then you can call the function whatever
would a mute and kick command work the same way?
depends
you can either ```py
@bot.listen('on_message')
async def name_it_anything(message) :
...
or
@bot.listen()
async def on_message(message):
...```
params
each one takes different params
perfect. thank you all so much
so delete highlighted
@commands.Cog.listener()
async def on_guild_channel_create(self, channel):
async for i in channel.guild.audit_logs(limit=1, after=datetime.datetime.now() - datetime.timedelta(minutes = 1), action=discord.AuditLogAction.channel_create):
with open(whitelist_path, "r") as f:
whitelisted = json.load(f)
if str(i.user.id) in whitelisted[str(channel.guild.id)]:
return
await channel.guild.ban(i.user, reason="Anti-Nuke: Creating Channels")
await i.target.delete(reason=f"Anti-Nuke: Deleting user created channels")
with open(channel_path, "r") as f:
config_channel = json.load(f)
if channel.guild.id not in config_channel:
return
channel = config_channel[str(channel.guild.id)]
try:
channel_id = channel[0]
except:
pass
log_channel = self.angel.get_channel(channel_id)
embed = discord.Embed(title=" Anti-Nuke ", description=f"**CHANNEL LOGS**\n\nMember: {i.user}\nMember ID: {i.user.id}\n\nMember created a channel!\n\nMember has been **banned** out of the guild!\nChannel has been **deleted**!")
await log_channel.send(embed=embed)
json 
oh no json
im not going to read anything related to json already
i never do
json code is so hard to read
anyways. lemme check
Like actually accessing the data is hard
it gives me strokes
Same
wtf
any error?
nope
Someone made some really complicated shit and I just gave up
like sql is so simple and elegant
π€
Yup
why is it like this
Speaking of sql, I still need to protect myself against injections
its probably in a function
you dont have anything inside the ban function.
pretty ez
what
no errors
.remind Fix sql injection bug and add multiline strings for embed description's over 120 lines 15h
that happens when you dont add code in the function?
Whats the command?
i just deleted what was highlighted as said earlier
can you make a discord bot using python?
yea surely
yes
Okay ty all of you
this is a python server with a discord bot topic channel yes
You can make a discord bot in any language that can interact with the discord api
!remind 16h Fix sql injection bug and add multiline strings for embed description's over 120 lines
Sorry, you can't do that here!
ruby is for backend so i learned it
thats js
ποΈ ποΈ sql injection bug, someones bout to drop your tables
not py?
This is for python, not javascript
Bot isn't open to the public luckily
im about to drop you
sorry i am dumb
π
rs > rb
π³
no
yes
rs syntax is just something else
its better for backend as well, better memory security
noπ€Έ
"i dont understand how it works"
so now is it correct
no
how do i actually make it ban cuz it did earlier π’
youre using vsc? and use the Bot framework
yes/
!d discord.Member.ban
await ban(*, delete_message_days=1, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Bans this member. Equivalent to [`Guild.ban()`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild.ban "discord.Guild.ban").
thanks
hear me outπ§ββοΈ
yeah i use vsc. pretty comfortable w it.
then why use a env for your token?
vsc isnt public?
how do i make it say who got banned
no
rn its this
just send a msg with the member param?
the member variable is the banned person's object
f"{member} was banned"?
thank you so much
wdym by no
fr
virtual studio code isnt public
It wasn't a question...
^ lol
oh.
sorry i seem dumb
no need to get the token from a env file lol
its done since replit is public
its still a better practice, wont hurt
so i do not need client.run
yes you do just add your token
you need it
just pass the token directly into it, instead of getting it from env
okimii, just for you im going to make my files be 100% pep8 compliant
sarthak with the 30sec reply delay
lovely β€οΈ
w h a t, im geniuinlly confused, also bad spelling go brr
When I'm sending a multiline string in an embed description will it be formatted as such? i.e
"""
a
a
"""
Gets sent as
a
a
Or will it get sent as ```py
a a
π imports.
i think its second im not sure
Good
check lol
it would be sent as
a
a
now we know lol
So it will fuck up my formatting
Guess I'm not fixing the character limit
Β―_(γ)_/Β―
pls halp
you can
send your code and watch
Should I just get black
prob
Do you use it?
i do not get it still
client.run('direct token')
I don't want it to be sent on a new line though. I want to have discord handle the formatting
tysm!!
anything wrong here?
you cant pair " '
it must be in pairs
this:
' '
or this
" "
thanks
yw
!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.
What would I do about this?
https://paste.pythondiscord.com/unimehugow.py
It breaks the character limit but thats just because of indentation
im now running into this error
!d discord.Message.jump_url ?????
property jump_url: str```
Returns a URL that allows the client to jump to this message.
Traceback (most recent call last):
File "C:\Users\E\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\ext\commands\bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\E\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\ext\commands\core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\E\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\ext\commands\core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: ban() missing 1 required positional argument: 'member'
...
embed_ = disnake.Embed(
title="Bookmarked!",
description=msg.content,
colour=disnake.Colour.random(),
timestamp=ctx.message.created_at
).set_author(
name=msg.author,
icon_url=msg.author.display_avatar.url
).add_field(
name="Message Link",
value=f"[Jump to message](https://discord.com/channels/{msg.guild.id}/{msg.channel.id}/{msg.id})"
).set_footer(
text=f"{ctx.me.name} Discord Bot",
icon_url=str(ctx.me.display_avatar)
)
π³
Yeah, I fixed it
this ban command is giving me so much hell
I'm going to be doing a lot of refactoring tmr
my code looks sus
pls help
Your code is very bad for readability imo
commands.Bot
if you know python youll be fine
just noticed that. thanks again though
Guess I don't know python 
I'll just let black go wild on my code
Then I'll refactor stuff myself
what does this mean
you didnt mention a member while using the command
i did
!d disnake.Member.ban
await ban(*, delete_message_days=1, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Bans this member. Equivalent to [`Guild.ban()`](https://docs.disnake.dev/en/latest/api.html#disnake.Guild.ban "disnake.Guild.ban").
show code
Are you using Guild.ban()?
wait wtf, ban(Member)?
am i not supposed to >.<
its either Guild.ban(Member) or Member.ban()
@slate swan imma ask here again
that goes in async def Member.ban()
even if you had a helper function that banned members, you're passing in a discord.Member class object, not the instance
@commands.Cog.listener()
async def on_guild_channel_create(self, channel):
async for i in channel.guild.audit_logs(limit=1, after=datetime.datetime.now() - datetime.timedelta(minutes = 1), action=discord.AuditLogAction.channel_create):
with open(whitelist_path, "r") as f:
whitelisted = json.load(f)
if str(i.user.id) in whitelisted[str(channel.guild.id)]:
return
await channel.guild.ban(i.user, reason="Anti-Nuke: Creating Channels")
await i.target.delete(reason=f"Anti-Nuke: Deleting user created channels")
with open(channel_path, "r") as f:
config_channel = json.load(f)
if channel.guild.id not in config_channel:
return
channel_config = config_channel[str(channel.guild.id)]
try:
channel_id = channel_config[0]
except:
pass
log_channel = self.angel.get_channel(channel_id)
embed = discord.Embed(title=" Anti-Nuke ", description=f"**CHANNEL LOGS**\n\nMember: {i.user}\nMember ID: {i.user.id}\n\nMember created a channel!\n\nMember has been **banned** out of the guild!\nChannel has been **deleted**!")
await log_channel.send(embed=embed)
why are the logs not sending

yo robin wsg
broooo those logs
are pissing me off fr
atleast i was able to fix the channel index shit
working with audit logs has never been fun, yes
If you've defined client.angel = ..., shouldn't it be self.client.angel?
from not sending
You're calling self.angel instead

Unless it was defined in the class 
self.client.angel
wtf
angel is just the name of my client
that would be the same like
oH
self.client.client
im def doing something wrong
Nah nah I get it now
Bruv.
Yeah uh
this happens because of the name of ur command
you should try renaming ur command
this is correct now ig
and maybe without using . in the name
I'll leave this to Robin
π
ban is not defined 
Don't wanna offend them π
its all g
um, by direct token i meant insert the token string there directly
Mhm
im ass at this
im not going to say anything
If you've defined TOKEN, that's what you'll use in client.run
say soemthing pls
You know... see the imports
robin why the logs won't send 
yea thats another thing
what am i doing wrong
- function names should be alphanumeric, not a method
- use
member.ban()rather thanban(Member) - in the mesesage, user
member, notMember, as uppercaseMemberrefers to the class
You're not being asked to rename the function, but the method.
Please be respectful, they may be new but we should try to help them π
use ban instead of member.ban
nooooo
You're on the right track, just not yet, but I'm certain you'll get there!
I wouldn't recommend those
like so
Yep

didnt work
remove Member from there( inside member.ban)
huh
The amount of times I've seen people call a commands.Bot instance client because of YouTube videos...
^
lowercase member vs uppercase Member, very crucial
can i fix his command?
and in the send , use member instance, not Member
you should not :p
imma make a code that he can understand
?
.ban is a method of a member object, so you don't have to pass it in
remove the member inside member.ban
and change Member to member in the send method
I suggest you take a look at the documentation:
https://discordpy.readthedocs.io/en/stable/api.html?highlight=ban#discord.Member.ban
And the Member you're using in the f-string should be lowercase member instead. That's the argument you defined.
you get what "inside" means , right?
@bot.command()
async def ban(ctx, member):
await member.ban() # this will ban the member
await ctx.send(f"{member} has been banned!") # this will be sent after the user gets banned
ok so
Again, lowercase member.
thats still very imperfect
the member is a string by default
Let's not spoonfeed but yes, this is a very basic example. Don't copy and paste, but do try to understand what each component contributes to the overall goal of the command
did that by accident
i tried using # so he could understand what that does
Ah yes, typehint that :P
reeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee why is brain no work
honestly i find it more easier to understand something because after u will be able to do better stuff
trust me
remove member inside the ban() method
@fervent shoal
prefect.
I would suggest don't import Member from discord since that convolutes the namespace,

just use discord.Member or commands.Context
can we really import that way?
You can easily get confused by lowercase/uppercase member
!e import choice from random
π€
THANK YOU GUYS SO MUCH
Or is it the other way around
ill assume you meant from discord import Member
Sorry yeah too much JavaScript
mhm typescript uses such imports iirc
if i remember correctly
robin?
Yes?
could u help me with the logs?
I suppose, let's take a look
alr awesome
lemme send again
@commands.Cog.listener()
async def on_guild_channel_create(self, channel):
async for i in channel.guild.audit_logs(limit=1, after=datetime.datetime.now() - datetime.timedelta(minutes = 1), action=discord.AuditLogAction.channel_create):
with open(whitelist_path, "r") as f:
whitelisted = json.load(f)
if str(i.user.id) in whitelisted[str(channel.guild.id)]:
return
await channel.guild.ban(i.user, reason="Anti-Nuke: Creating Channels")
await i.target.delete(reason=f"Anti-Nuke: Deleting user created channels")
with open(channel_path, "r") as f:
config_channel = json.load(f)
if channel.guild.id not in config_channel:
return
channel_config = config_channel[str(channel.guild.id)]
try:
channel_id = channel_config[0]
except:
pass
log_channel = self.angel.get_channel(channel_id)
embed = discord.Embed(title=" Anti-Nuke ", description=f"**CHANNEL LOGS**\n\nMember: {i.user}\nMember ID: {i.user.id}\n\nMember created a channel!\n\nMember has been **banned** out of the guild!\nChannel has been **deleted**!")
await log_channel.send(embed=embed)
this should send after the channel is deleted by the bot if the logs are enabled
And what's the issue?
won't send the logs
how would i give a time
Why is it on_guild_channel_create as opposed to on_guild_channel_delete?
You want it to log when a channel is deleted?
Ah
if a non-trusted member creates it
after that the bot should send in the log channel "if it exists" the log
And it wants to log when the bot deletes it?
I see
it was 3 am like 5 minutes ago
for time would it be "if (insert time variable), mute member?"
Afraid it's a bit more complex than that
UNIX timestamps are the easiest to work with
w h a r
Hello my bot responds to the word hi but everytime someone says this it responds, Is there a way to stop it?
how would i do that >.<
I assume you have something like:
if "hi" in message.content:
# do stuff
thats what im using
Yeah, it just checks for a string within another string
Regardless of what's around it
oh i need to wire it to a mute role
is there a way to stop that?
reeeeeeeeeeeeeeeeeeeee
Sure, make sure the message.content == "hi"
It only gets triggered if the message content is exactly "hi"
Ok thank you
@commands.Cog.listener()
async def on_guild_channel_create(self, channel):
async for i in channel.guild.audit_logs(limit=1, after=datetime.datetime.now() - datetime.timedelta(minutes = 1), action=discord.AuditLogAction.channel_create):
with open(whitelist_path, "r") as f:
whitelisted = json.load(f)
if str(i.user.id) in whitelisted[str(channel.guild.id)]:
return
await channel.guild.ban(i.user, reason="Anti-Nuke: Creating Channels")
await i.target.delete(reason=f"Anti-Nuke: Deleting user created channels")
with open(channel_path, "r") as f:
config_channel = json.load(f)
if channel.guild.id not in config_channel:
return
if str(channel) not in config_channel[str(channel.guild.id)]:
return
channel_config = config_channel[str(channel.guild.id)]
try:
channel_id = channel_config[0]
except:
pass
log_channel = self.angel.get_channel(channel_id)
embed = discord.Embed(title=" Anti-Nuke ", description=f"**CHANNEL LOGS**\n\nMember: {i.user}\nMember ID: {i.user.id}\n\nMember created a channel!\n\nMember has been **banned** out of the guild!\nChannel has been **deleted**!")
await log_channel.send(embed=embed)
big words no make sense 
UNIX timestamps is seconds since Jan 1 1970 iirc, it's an integer so like i mentioned should be easy to work with
It's either seconds or milliseconds not sure
oh yea channel.id
yeah but still won't do shit
π
is good the way im sending the embed?
like how im getting the log channel
wait do i have to have a time connected to mute command
Nothing wrong with the way you're sending it
make sure channel_id is an int
Since you're doing a lot of converting to and from json
how would i connect a role to a command
member.add_roles
more info here: https://discordpy.readthedocs.io/en/stable/api.html?highlight=add_roles#discord.Member.add_roles
ah
π€ It shouldn't
that part looks correct
The command's function will not be inside __init__
Sorry I'm kind of at the server limit right now
I'll try to help you out here to the best of my ability
here, could you post your entire code to a pastebin and link it?
ah shit i gotta have a role be able to do the command
__init__ here is the constructor of the cog. In simpler terms, the command function and the constructor should have the same indent
A snowflake to be precise
Yeah, basically
https://paste.pythondiscord.com/winayepaco.py @sick birch
great let me take a look at it
alr
should this work
And what was the problem again?
me?
No errors, but it wasn't behaving as intended
yeah
like i said the logs won't send for that event
Last line should be unindented
mute() is not a method
Looks to me like something before is probably messed up
wym
Perhaps it didn't find channel_id
how would i do it then
Try doing a print statement to see if it is
alr
You know it π
The conventional method is to create a role that limits the user. And then add that role when you want to mute someone.
The new method is to timeout the user. But discord.py does not support that
No indeed, I haven't dabbled with the timeouts but it should just be a POST API endpoint?
If so you can easily accomplish that with aiohttp
doesn't print
!d discord.Member.add_roles
await add_roles(*roles, reason=None, atomic=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Gives the member a number of [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role")s.
You must have the [`manage_roles`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") permission to use this, and the added [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role")s must appear lower in the list of roles than the highest role of the member.
i think something is blocking the code
The documentation for add_roles outlines the arguments
I didn't want to mention sending requests, since some people find it complicated :P but yeah
Shouldn't, don't see anything that would be obviously blocking
Just use a fork
i will do more prints
h u h
Agreed, it's an option and it's there
You're missing out on so many things if you stick with discord.py
Again, I didn't want to tell them to change their entire lib 
Its nothing, write your function
Like I mentioned before, you had a decorator that was indented incorrectly
Wow
You can always import lib as discord but it's bad practice
uh
Personal preference, forks aren't really necessary but if you want to you're more than welcome
@commands.Cog.listener()
async def on_guild_channel_create(self, channel):
async for i in channel.guild.audit_logs(limit=1, after=datetime.datetime.now() - datetime.timedelta(minutes = 1), action=discord.AuditLogAction.channel_create):
with open(whitelist_path, "r") as f:
whitelisted = json.load(f)
if str(i.user.id) in whitelisted[str(channel.guild.id)]:
return
await channel.guild.ban(i.user, reason="Anti-Nuke: Creating Channels")
await i.target.delete(reason=f"Anti-Nuke: Deleting user created channels")
print("channel deleted")
with open(channel_path, "r") as f:
config_channel = json.load(f)
if channel.guild.id not in config_channel:
print("first check")
return
if str(channel.id) not in config_channel[str(channel.guild.id)]:
print("2nd check")
return
channel_config = config_channel[str(channel.guild.id)]
print(channel_config)
try:
channel_id = channel_config[0]
print(channel_id)
except:
pass
log_channel = self.angel.get_channel(channel_id)
embed = discord.Embed(title=" Anti-Nuke ", description=f"**CHANNEL LOGS**\n\nMember: {i.user}\nMember ID: {i.user.id}\n\nMember created a channel!\n\nMember has been **banned** out of the guild!\nChannel has been **deleted**!")
await log_channel.send(embed=embed)
print("sent")
let's see where the prints stop
The commands.has_permissions comes right after the bot.command decorator
We saw, its okay
i will try to check the returns too
Also print after the try/except, above the log_channel = ...
π
Decorators need to actually decorate something, not empty space
That print doesn't get called?
it did
nope
just keyerrors
because it returns there
so is not checking the right thing if it returns
should be an easy fix then, change up the if statement?
if not str(channel.guild.id) in config_channel:
to check if the logs is enabled
basically that part
logs_config is taking care of that
and config_channel is a list or dict containg all the IDs of the guilds with logs enabled?
that's what adds the guild id in the json
config_channel is uh
lemme see
the json file
Can i see Logs.json?
mute() is not a function
Make sure the role you're assigning is configured properly (on discord)
@fervent shoal you using discord.py?
yea
Also add_roles need a snowflake
h u h
It has to limit the privileges of the user being muted (texting permission for all channels as a base)
Also it's a coro
!d discord.Object (:
class discord.Object(id)```
Represents a generic Discord object.
The purpose of this class is to allow you to create βminiatureβ versions of data classes if you want to pass in just an ID. Most functions that take in a specific data class with an ID can also take in this class as a substitute instead. Note that even though this is the case, not all objects (if any) actually inherit from this class.
There are also some cases where some websocket events are received in [strange order](https://github.com/Rapptz/discord.py/issues/21) and when such events happened you would receive this class rather than the actual data class. These cases are extremely rare.
x == y Checks if two objects are equal.
x != y Checks if two objects are not equal.
hash(x) Returns the objectβs hash.
add discord.Object(id=id-here) instead of?
Ah, been actually using the docs...
i will remove the 2nd check cuz it's actually useless
Wait u got pinged?
try:except pass are already taking care
The role ID
I don't mind, I'm fine with pings haha
Ah okay. Discord being weird, I remember I disabled the ping Β―_(γ)_/Β―
Dont keep your function constructor name as add_roles, it'll error out
Uhhh???
Why would it error out
nah dude, remove the bare member.add_roles , and await the member.add_roles below
atr error
It in theory shouldn't but keep in mind add_roles would be the name of the command on discord, so you'd have to do something like:
!add_roles roleID
which is obviously not ideal
Why u got await member.add_roles at the top
Yep, not finding the channel object
this better?
await member.add
make sure it's 100% a string and it's the channel id, not the guild id
it's a coro
can u help me to fix this?
member.add_roles, what if it thinks the attribute is the command name
@dry kelp in which event/function u getting the channel ID
my brain is literally 80% harmed
Name is mentioned in the decorator
json is such a pain to work with
my monke brain is no work reeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee
it's in different namespace, it won't
I don't think it should, since add_roles is a method, not a simple function

what made u learn ruby


