client.(variable) variables in Discord.py Cogs - python-3.x

I am facing an issue while migrating my python code to discord.py.
The issue is, I don't know how to use client. variables in discord.py cogs like client.sniped_messages = {}...
It shows an error -
Traceback (most recent call last):
File "C:\Users\arjun\Documents\Arjun\Python\discord.py\swayde\main.py", line 55, in <module>
client.load_extension(f"cogs.{filename[:-3]}")
File "C:\Users\arjun\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 678, in load_extension
self._load_from_module_spec(spec, name)
File "C:\Users\arjun\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 609, in _load_from_module_spec
raise errors.ExtensionFailed(key, e) from e
discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.Utility' raised an error: NameError: name 'self' is not defined
Here's the code -
import discord
from discord.ext import commands
import random
import datetime
class Utility(commands.Cog):
def __init__(self, client):
self.client = client
self.client.sniped_messages = {}
#commands.Cog.listener()
async def on_message_delete(self,message):
self.client.sniped_messages[message.guild.id] = (message.content, message.author, message.channel.name, message.created_at)
#commands.command()
async def snipe(self, ctx):
try:
contents, author, channel_name, time = self.client.sniped_messages[ctx.guild.id]
except:
await ctx.channel.send("Couldn't find a message to snipe!")
return
embed = discord.Embed(description=contents, color=discord.Color.purple(), timestamp=time)
embed.set_author(name=f"{author.name}#{author.discriminator}", icon_url=author.avatar_url)
embed.set_footer(text=f"Deleted in : #{channel_name}")
await ctx.channel.send(embed=embed)
def setup(client):
client.add_cog(Utility(client))
Now, when I delete the variable client.sniped_messages = {}, The code runs perfectly.
Please tell me how I can resolve this issue and how to use .client variables in cogs.
Thanks in advance!

You have to indent self.client.sniped_messages = {} so it's inside the __init__ method
def __init__(self, client):
self.client = client
self.client.sniped_messages = {}

Related

trying to make a cogs loader doscord.py

I am trying to make a command which will load a certain cogs from cog folder.
I have followed a youtube tutorial
https://youtu.be/vQw8cFfZPx0
but I am getting some errors and I don't know how to fix it
import discord
import os
from discord.ext import commands
client = commands.Bot(command_prefix= "#")
#client.command()
async def load(ctx, extension):
client.load_extension(f'cogs.{extension}')
#client.command()
async def unload(ctx, extension):
client.unload_extension(f"cogs.{extension}")
#client.command
async def reload(ctx, extension):
client.reload_extension(f"cogs.{extension}")
for filename in os.listdir('./cogs'):
if filename.endswith('.py'):
client.load_extension(f'cogs.{filename[:-3]}')
client.run('token')
and this is my cog file
import discord
from discord.ext import commands
class Example(commands.cog):
def __init__(self, client):
self.client = client
#event
#commands.Cog.listener()
async def on_ready(self):
print("bot is online")
#commands.command()
async def ping(self, ctx):
await ctx.send("pong")
def setup(client):
client.add_cog(Example(client))
and this is the error I am getting
Traceback (most recent call last):
File "c:\Users\...\Discord bot\cogs\ping.py", line 4, in <module>
class Example(commands.cog):
TypeError: module() takes at most 2 arguments (3 given)
btw I am new to python so I may have done very silly mistake
Since Cog is a class, and classes use the CapWords convention:
class Example(commands.Cog): # instead of class Example(commands.cog):
commands.cog should be commands.Cog
The c in Cog has to be capital

Message in a specific Discord channel

Hi guys i'm trying to make the bot send a message automatically in a specific channel. I took the channel ID and pass it in the if condition (a_string.find ('data: []')! = -1). However this code gives me this error. See OUTPU ERROR.
P.S. I'm using Replit and Live is the file name (Live.py)
from discord.ext import commands
from Naked.toolshed.shell import execute_js, muterun_js
import sys
class Live(commands.Cog):
def __init__(self,client):
self.client=client
#commands.Cog.listener()
async def on_ready(self):
channel = self.get_channel(828711580434169858)
response = muterun_js('serverJs.js')
original_stdout = sys.stdout # Save a reference to the original standard output
if response.exitcode == 0:
a_string= str(response.stdout)#stampa in console
if (a_string.find('data: []') != -1):
print("Streamer: Offline ")
else:
print("Streamer: Online")
await channel.send('Live Link: https://...link....')
else:
sys.stderr.write(response.stderr)
#commands.command()
async def Live(self,ctx):
await ctx.send('')
def setup(client):
client.add_cog(Live(client))
OUTPUT ERROR:
Ignoring exception in on_ready
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "/home/runner/Solaris-IA/cogs/Live.py", line 12, in on_ready
channel = self.get_channel(828711580434169858)
AttributeError: 'Live' object has no attribute 'get_channel'
It's self.client.get_channel, not self.get_channel, you haven't defined that function
channel = self.client.get_channel(828711580434169858)

How to import functions from different file and use in discord.py

A straight Forward question - How to import a function from a different file and use that in discord.py cuz i tried that and failed for example there is file a and b which looks like
a.py:
async def joke(ctx):
joke = 'Your mama so fat boy'
await ctx.send(joke)
and i want to use the joke function from file a to file b and the code i write was:
from a import joke
from discord.ext import commands
#some discord code
TOKEN = 'My_Secret_Token'
GUILD = 'My_Guild'
client = commands.Bot(command_prefix='!')
#client.command(name='joke', help='This will return a joke')
joke()
client.run(TOKEN)
And the line joke() is returning me error
File "main.py", line 31
joke()
^
SyntaxError: invalid syntax
And i am here confused that why it is returning me error and how can i pass the argument ctx. So please come up with a solution for me.
Edit: After debugging and scratching my head for hours i came up with a solution which is also not working that i modified my b.py a little bit :
from a import joke
from discord.ext import commands
#some discord code
TOKEN = 'My_Secret_Token'
GUILD = 'My_Guild'
client = commands.Bot(command_prefix='!')
#client.command(name='joke', help='This will return a joke')
async def my_function(ctx):
joke(ctx)
client.run(TOKEN)
You can use cogs for this. Docs: https://discordpy.readthedocs.io/en/latest/ext/commands/cogs.html
Here is an Example:
Your main.py
import discord
from discord.ext import commands
import os
client = commands.Bot(command_prefix='!')
for file in os.listdir("cogs"):
if file.endswith(".py"):
name = file[:-3]
client.load_extension(f"cogs.{name}")
client.run(TOKEN)
Make a secound /cogs/joke.py
import discord
from discord.ext import commands
import random
class joke(commands.Cog):
def __init__(self, bot):
self.bot = bot
#commands.command()
async def joke(self, ctx):
jokes = [
'Your mama so fat boy',
'joke2',
'joke3',
'joke4',
'joke5'
]
answer = random.choice(jokes)
await ctx.send(answer)
def setup(bot):
bot.add_cog(joke(bot))

Callback for join command is missing "ctx" parameter

I'm trying to make a music cog for my bot. I'm currently making commands for the bot to join and leave a voice channel. But everytime i try to launch both of these commands, the same error occurs.
Ignoring exception in on_message
Traceback (most recent call last):
File "C:\Users\Daniel\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\core.py", line 663, in _parse_arguments
next(iterator)
StopIteration
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\Daniel\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\client.py", line 312, in _run_event
await coro(*args, **kwargs)
File "C:\Users\Daniel\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\bot.py", line 930, in on_message
await self.process_commands(message)
File "C:\Users\Daniel\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\bot.py", line 927, in process_commands
await self.invoke(ctx)
File "C:\Users\Daniel\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\bot.py", line 892, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\Daniel\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\core.py", line 790, in invoke
await self.prepare(ctx)
File "C:\Users\Daniel\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\core.py", line 751, in prepare
await self._parse_arguments(ctx)
File "C:\Users\Daniel\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\core.py", line 666, in _parse_arguments
raise discord.ClientException(fmt.format(self))
discord.errors.ClientException: Callback for join/leave command is missing "ctx" parameter.
Here's the code i have:
import discord
from discord.ext import commands
import youtube_dl
class Music(commands.Cog):
def __init__(self, client):
self.client = client
#commands.command()
async def join(ctx):
channel = ctx.message.author.voice.channel
await channel.connect()
#commands.command()
async def leave(ctx):
await ctx.voice_client.diconnect()
def setup(client):
client.add_cog(Music(client))
Anyone know how i can fix this ?
You need to put self in your function async def join as well as your leave function:
#commands.command()
async def join(self, ctx):
channel = ctx.message.author.voice.channel
await channel.connect()
You're using a cog so you have a class with self that must be passed to classes not decorated with #staticmethod or #classmethod. With discord.py I recommend you do not do either of those for command/event functions you have above.
See: https://discordpy.readthedocs.io/en/latest/ext/commands/cogs.html
For cogs in discord.py

Python3 Discord Module No Attribute Client

I was handed a Python Discord Message Mass Prune Script in Py3.
But there were a few errors, Prior to this.
It was working before, but now it's giving me some error that
it didn't give me before.
import discord
import asyncio
client = discord.Client()
#client.event
async def on_ready():
print(' ')
print('Lorem')
print('ipsum')
print('dolor')
print('amet')
print('sit')
print('consectetur')
print('Logged in as:', client.user.name)
print('UID:',client.user.id)
print('Discord version:',discord.__version__)
print('----------')
print('Connected to:')
for server in client.servers:
print(' -',server.name)
# Define commands
#client.event
async def on_ready():
if message.author == client.user:
commands = []
z = 0
for index, a in enumerate(message.content):
if a == " ":
commands.append(message.content[z:index])
z = index+1
commands.append(message.content[z:])
# MASS DELETE OWN MESSAGES
if commands[0] == 'xc':
if len(commands) == 1:
async for msg in client.logs_from(message.channel,limit=9999):
if msg.author == client.user:
try:
await client.delete_message(msg)
except Exception as x:
pass
elif len(commands) == 2:
user_id = ''
for channel in client.private_channels:
if commands[1] in str(channel):
if str(channel.type) == 'private':
user_id = str(channel.id)
async for msg in client.logs_from(discord.Object(id=user_id),limit=9999):
if msg.author == client.user:
try:
await client.delete_message(msg)
except Exception as x:
pass
client.run("TOKEN HERE",bot=False)
Using Py3 Pip, I installed discord and asyncio (The required modules) needed for the script.
At line 4 (client = discord.Client())
It throws off the error
Traceback (most recent call last):
File "discord.py", line 1, in <module>
import discord
File "C:\Program Files\Python36\discord.py", line 4, in <module>
client = discord.Client()
AttributeError: module 'discord' has no attribute 'Client'
Your program is called discord.py. That is masking the real discord module. Call the program something else.
Change your file name from discord.py to another like discord_message.py
AS it is importing discord from your os only

Resources