discord.py lots of "cog" errors - python

trying to make a global banning system with cogs but it gives me cog errors and im not too good with cog. the code is from an old github repo by the way so i dont take credit for this.
bot.py:
import discord
import os
import json
from discord.ext import commands
client = commands.Bot(command_prefix = ".")
client.remove_command("help")
#client.event
async def on_ready():
print("Global Banning System is online!")
for filename in os.listdir("cogs"):
if filename.endswith(".py"):
client.load_extension(f"cogs.gbs")
client.run(token)
and i also have another file in a new folder ("cogs") that is called "gbs.py".
gbs.py:
import discord
from discord.ext import commands
class gbs(commands.Cog):
def __init__(self, client):
self.client = client
#commands.command()
#commands.has_role(roleid) # Staff's Role
async def gban(self, ctx, member: discord.User):
channel = self.client.get_channel(channelid) # Logs
auth = ctx.author
await ctx.send("Ban Issue successfuly opened. Now, please type the ban reason!")
reason = await self.client.wait_for('message', timeout = 600)
embed = discord.Embed(title = f"Global Banned {member.name}", colour = 0xFF0000)
embed.add_field(name = "Reason:", value = reason.content, inline = False)
embed.add_field(name = "User ID:", value = f"`{member.id}`",)
embed.add_field(name = "Staff Member:", value = f"{auth.name}")
embed.set_thumbnail(url = member.avatar_url)
await ctx.send(embed = embed)
await ctx.send(f"**{member.name}** has been globbaly banned!")
for guild in self.gbs.guilds:
await guild.ban(member)
def setup(client):
gbs.add_cog(gbs(client))
This is the errors that it gives me.
Traceback (most recent call last):
File "C:\Users\user-01\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\cog.py", line 723, in _load_from_module_spec
setup(self)
File "C:\Users\user-01\Desktop\Global Banning System - Discord Bot\cogs\gbs.py", line 28, in setup
gbs.add_cog(gbs(client))
AttributeError: type object 'gbs' has no attribute 'add_cog'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\user-01\Desktop\Global Banning System - Discord Bot\bot.py", line 15, in <module>
client.load_extension(f"cogs.gbs")
File "C:\Users\user-01\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\cog.py", line 783, in load_extension
self._load_from_module_spec(spec, name)
File "C:\Users\user-01\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\cog.py", line 728, in _load_from_module_spec
raise errors.ExtensionFailed(key, e) from e
discord.errors.ExtensionFailed: Extension 'cogs.gbs' raised an error: AttributeError: type object 'gbs' has no attribute 'add_cog'

You add a cog class to your bot not to your gbs. So replace gbs with client to solve the problem.
def setup(client):
# instead of gbs.add_cog...
client.add_cog(gbs(client)
Documentation

Related

Why won't my bot send messages to specific channels? Discord.py channel = bot.get_channel()

Discord Bot Not Sending Messages To Specified Channels
Hello,
I'm creating a discord bot to log actions and send them to specific channels. Every time I run my code I get no errors but as soon as I type in the command/word used I get an error. I am just trying to log actions into another channel.
I haven't set this section up yet:
bot = discord.ext.commands.Bot(command_prefix = "$");
Here is my code:
import os
import discord
from discord.ext import commands
bot = discord.ext.commands.Bot(command_prefix = "$");
client = discord.Client()
# #client.event
# async def on_message(message):
# id = client.get_guild(940403791092670464)
#client.event
async def on_ready():
print(f"{client.user} logged in now!")
#client.event
async def on_message(message):
if message.content.startswith("$help"):
response = print (f"#help command was used")
await message.channel.send(f"{message.author.mention} help stuff")
elif "fudge" in message.content:
await message.delete()
response = print(f"You're not allowed to say those words {message.author.mention} Word Used: Fudge")
await message.channel.send(f"You're not allowed to use those words {message.author}.")
elif "female dog" in message.content:
channel = bot.get_channel(943040534165991485)
await channel.send(f"{message.author.mention} Said the word female dog.")
await message.channel.send(f"You're not allowed to say those words {message.author.mention}")
await message.delete()
response = print (f"Logging actions.")
my_secret = os.environ['TOKEN']
client.run(my_secret)
Here is my Err:
Ignoring exception in on_message
Traceback (most recent call last):
File "/home/runner/Discord-Bot/venv/lib/python3.8/site-packages/discord/client.py", line 343, in _run_event await coro(*args, **kwargs)
File "main.py", line 31, in on_message
await channel.send(f"{message.author.mention} Said the word Food.")
AttributeError: 'NoneType' object has no attribute 'send'
Anything helps!
Use fetch_channel() instead of get_channel(). In discord.py as a rule of thumb fetch_something() makes an API call while get_something() tries to get it from the cache.

ffempeg discord bot python

So I want to play local files in my discord voice channel, right now it joins the voice channel but it does not play anything. This is the code:
if message.content.startswith('$Hest'):
where = message.content.split(" ")[1]
channel = get(message.guild.channels, name=where)
voicechannel = await channel.connect()
voicechannel.play(discord.FFempegPCMAudio(executable='D:/ffmpeg/ffmpeg/bin/ffplay.exe', source='D:/ffmpeg/Horse.mp3'))
And this is my output when I try to do it
Traceback (most recent call last):
File "F:\Apanda\CustomMultiPyBot\venv\lib\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "F:/Apanda/CustomMultiPyBot/main.py", line 41, in on_message
voicechannel.play(discord.FFempegPCMAudio(executable='D:/ffmpeg/ffmpeg/bin/ffplay.exe', source='D:/ffmpeg/Horse.mp3'))
AttributeError: module 'discord' has no attribute 'FFempegPCMAudio'
This issue is just that you are trying to use discord.FFempegPCMAudio when the class is actually discord.FFmpegPCMAudio.
So to correct your code:
if message.content.startswith('$Hest'):
where = message.content.split(" ")[1]
channel = get(message.guild.channels, name=where)
voicechannel = await channel.connect()
voicechannel.play(
discord.FFmpegPCMAudio(
'D:/ffmpeg/Horse.mp3',
executable='D:/ffmpeg/ffmpeg/bin/ffplay.exe'
)
)
And if you wanted to restructure this to use the discord.ext.commands framework, your code would look something like this:
import discord
from discord.ext import commands
bot = commands.Bot(command_prefix="$")
#bot.command(name="Hest")
async def hest(ctx, where):
channel = discord.utils.get(ctx.guild.channels, name=where)
voicechannel = await channel.connect()
voicechannel.play(
discord.FFmpegPCMAudio(
'D:/ffmpeg/Horse.mp3',
executable='D:/ffmpeg/ffmpeg/bin/ffplay.exe'
)
)
bot.run("<token>")

'NoneType' object has no attribute 'group' when trying to translate with the googletrans lib for a discord bot

I'm getting an error when trying to translate a messages' content (note that I did import the latest version of this: https://pypi.org/project/googletrans/), I've checked enough times and I think I'm doing it correctly
Full code:
import discord, googletrans, os, dotenv
from discord.ext import commands
from dotenv import load_dotenv
from googletrans import Translator
load_dotenv()
translate = Translator()
prefix = 'tb!'
bot = commands.Bot(command_prefix=prefix)
bot.remove_command("help")
client = discord.Client()
TOKEN = os.getenv('TOKEN')
#translationch = 822024643468460042
#bot.event
async def on_ready():
print(f'{bot.user.name} connected to Discord!')
await bot.change_presence(activity=discord.Game(name=f"Translating..."))
#bot.listen()
async def on_message(msg):
print(msg.content)
if msg.content == "": return
text_ = translate.translate(msg.content)
if text_.text == msg.content: return
else:
embed=discord.Embed(title="Translating...", description="Just a second...", color=0x545454)
msg = await msg.channel.send(embed=embed)
try:
emb=discord.Embed(title="Translation", color=0x00ff08)
emb.add_field(name=f"Sent by {msg.author}", value=f"`{msg.content}`\n`{text_.text}`", inline=False)
emb.set_footer(text=f"Sent from channel #{msg.channel.name}")
await msg.edit(embed=emb)
except:
i = msg.content
if i > 1800: i = "The message was too long to display!"
error=discord.Embed(color=0xff0000)
error.add_field(name="Error!", value=f"I couldn't translate **{msg.author}**'s message: `{i}`", inline=False)
await msg.edit(embed=error)
return
bot.run(TOKEN)
The error I'm getting:
Ignoring exception in on_message
Traceback (most recent call last):
File "C:\Users\borny\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\client.py", line 312, in _run_event
await coro(*args, **kwargs)
File "c:/Users/borny/Desktop/stuff/vscode_projects/translate-bot/main.py", line 24, in on_message
translate.translate(msg.content)
File "C:\Users\borny\AppData\Local\Programs\Python\Python38\lib\site-packages\googletrans\client.py", line 182, in translate
data = self._translate(text, dest, src, kwargs)
File "C:\Users\borny\AppData\Local\Programs\Python\Python38\lib\site-packages\googletrans\client.py", line 78, in _translate
token = self.token_acquirer.do(text)
File "C:\Users\borny\AppData\Local\Programs\Python\Python38\lib\site-packages\googletrans\gtoken.py", line 194, in do
self._update()
File "C:\Users\borny\AppData\Local\Programs\Python\Python38\lib\site-packages\googletrans\gtoken.py", line 62, in _update
code = self.RE_TKK.search(r.text).group(1).replace('var ', '')
AttributeError: 'NoneType' object has no attribute 'group'
Ok so using this (the fixed lib) solved my problem: https://pypi.org/project/google-trans-new/
There's also an released alpha about the official googletrans lib that has this bug patched, you can find more about it in this thread: googletrans stopped working with error 'NoneType' object has no attribute 'group'
New code:
import discord, google_trans_new, os, dotenv
from discord.ext import commands
from dotenv import load_dotenv
from google_trans_new import google_translator
load_dotenv()
translate = google_translator()
prefix = 'tb!'
bot = commands.Bot(command_prefix=prefix)
bot.remove_command("help")
client = discord.Client()
TOKEN = os.getenv('TOKEN')
translationch = 822024643468460042
#bot.event
async def on_ready():
print(f'{bot.user.name} connected to Discord!')
await bot.change_presence(activity=discord.Game(name=f"Translating..."))
#bot.listen()
async def on_message(msg):
if msg.content == "": return
text_ = translate.translate(msg.content)[:-1]
if text_ == msg.content: return
else:
embed=discord.Embed(title="Translating...", description="Just a second...", color=0x545454)
msg_ = await msg.channel.send(embed=embed)
try:
emb=discord.Embed(title="Translated!", color=0x00ff08)
emb.add_field(name=f"Sent by {msg.author}", value=f"`Text: {msg.content}`\n`Translation: {text_}`", inline=False)
await msg_.edit(embed=emb)
except:
i = msg.content
if len(i) > 1800: i = "The message was too long to display!"
error=discord.Embed(color=0xff0000)
error.add_field(name="Error!", value=f"I couldn't translate **{msg.author}**'s message: `{i}`", inline=False)
await msg_.edit(embed=error)
return
bot.run(TOKEN)

discord.py await "AttributeError: 'list' object has no attribute 'id'" while using add_roles

I was trying to create a bot using discord.py, and was trying to use the add_roles member function using discord.ext commands.
Here is my code:
import os
import discord
from dotenv import load_dotenv
from discord.ext import commands
load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')
GUILD = os.getenv('DISCORD_GUILD')
intents = discord.Intents.default()
intents.members = True
client = discord.Client(intents=intents)
#client.event
async def on_ready():
guild = discord.utils.get(client.guilds, name=GUILD)
print(
f'{client.user} is connected to the following guild:\n'
f'{guild.name} (id: {guild.id})'
)
members = guild.members
for member in members:
role = discord.utils.get(member.guild.roles, name='test 2')
await member.add_roles([role],False)
When it calls the "await member.add_roles([role], False)," it gives an error of the following:
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/discord/client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "/Users/tanay/Documents/Python CYOA/bot.py", line 31, in on_ready
await member.add_roles([role],False)
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/discord/member.py", line 676, in add_roles
await req(guild_id, user_id, role.id, reason=reason)
AttributeError: 'list' object has no attribute 'id'
I've been doing a bunch of internet searches and just can't find how to fix this. Does anyone know what I did wrong?
Thank you so much!
When you're adding one role, you don't have to put it in []. That's why you're getting this error. So you just have to remove the brackets.
...
for member in members:
role = discord.utils.get(member.guild.roles, name='test 2')
await member.add_roles(role)

Discord py │ Bot Give Role

I'm trying to make my bot give role after a command is being called but I'm not sure what is the right command. I searched online but every single one I tried gave an error. Anyone know the correct form of the command?
The code:
#iports the discord folder and commands for our bot
import discord
from discord.ext import commands
from discord import Member
from discord.ext.commands import has_permissions
from discord.ext import tasks
#sets the command prefix
Client = commands.Bot(command_prefix = ";")
#print Nuggie is ready in the console when the bot is activeted
#Client.event
async def on_ready():
await Client.change_presence(status=discord.Status.online, activity = discord.Game("With Your Mom"))
print("Nuggie is ready")
#Client.command()
async def setup_verification(ctx, arg):
channel_id = 768983636296204318
await clear(ctx)
Text = "send ;verify to this message to get verified and get access to the server!"
embedVar = discord.Embed(title = "Verify your identity", description = Text, color = 0xC311EF)
embedVar.add_field(name = "\u200B", value = "\u200B")
embedVar.add_field(name = "This proccess in crucial for the server.", value = "Without this, the server is exposed to raids." , inline=False)
await ctx.channel.send(embed=embedVar)
#await ctx.send(Text)
#Client.command()
async def verify(ctx):
channel = 768983636296204318
if discord.TextChannel.id == channel:
clear()
await ctx.send("This message is not available in this channel! Pls only use command where it's supposed to be!")
else:
author = ctx.message.author.name
#Role = discord.utils.get(author.server.roles, name="Member")
await Message.add_roles(author, "Member")
#roleRemove = get(user.server.roles, name='member')
await Client.remove_role(author, "Unverified")
await ctx.send(f"{author} you are verified!")
await asyncio.sleepdelay(s = 60)
clear(ctx, 2)
Client.run('My_Token')
and the error I get when I run verify is:
Ignoring exception in command verify:
Traceback (most recent call last):
File "C:\Users\roy\AppData\Roaming\Python\Python38\site-packages\discord\ext\commands\core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Users\roy\Desktop\Folders\Atom\Discord Bot\Nuggie.py", line 40, in verify
await Message.add_roles(author, "Member")
NameError: name 'Message' is not defined
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\roy\AppData\Roaming\Python\Python38\site-packages\discord\ext\commands\bot.py", line 903, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\roy\AppData\Roaming\Python\Python38\site-packages\discord\ext\commands\core.py", line 859, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\roy\AppData\Roaming\Python\Python38\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: NameError: name 'Message' is not defined
You need the Member object and you can call add_roles() on it. ctx.author is your Member object, now you need to get your Role object. There is different ways to get the Role object. You can get it by ID using Guild.get_role(role_id) or you can get it by name using discord.utils.get
memberRole = discord.utils.get(ctx.guild.roles, name='Member')
Now since you have your Member object and your Role object you can simply call Member.add_roles() on your Member object.
await ctx.author.add_roles(memberRole)
Same thing to remove the Unverified role, except you call Member.remove_roles()

Categories

Resources