AttributeError: 'Moderation' object has no attribute 'channel' - python-3.x

i tried to make cog for organize my bot but i have an error that i dont find how to fix. The bot successful find command in cog but when i write the command i have this error:
Could you help me pls ? Here is my code:
import discord
import asyncio
import re
import os
import random
from discord.ext import commands
class Moderation(commands.Cog):
def __init__(self, bot):
self.bot = bot
#Purge
#commands.command()
async def purge(ctx, amount=10):
await ctx.channel.purge(limit=amount)

Your first parameter must be self.
class Moderation(commands.Cog):
def __init__(self, bot):
self.bot = bot
#Purge
#commands.command()
async def purge(self, ctx, amount=10):
await ctx.channel.purge(limit=amount)

Add self as parameter in purge function.
async def purge(self,ctx,amount=10):
await ctx.channel.purge(limit=amount)

Related

How make discord.ext.tasks send in channel by id every x minutes in cogs

i tried
# -*- coding: utf-8 -*-
from discord.ext import commands
import discord
import random
import asyncio,json
from discord.ext.commands import clean_content
from datetime import datetime
import aiohttp
from discord.ext import tasks
class Test(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.test1.start()
#tasks.loop(minutes=1.0)
async def test1(self):
channel=bot.get_channel(927612404056092702)
channel.send(mensagem)
def setup(bot):
bot.add_cog(Test(bot))
using
channel=self.bot.get_channel(927612404056092702)
return AttributeError: 'NoneType' object has no attribute 'send'
and using
channel=bot.get_channel(927612404056092702)
return NameError: name 'bot' is not defined
bot.get_channel method retrives channel from cache. You can properly do it only after on_ready event:
class Test(commands.Cog):
def __init__(self, bot):
self.bot = bot
#tasks.loop(minutes=1.0)
async def test1(self):
channel=bot.get_channel(927612404056092702)
channel.send(mensagem)
#commands.Cog.listener()
async def on_ready(self):
if not self.test1.is_running():
self.test1.start()
def setup(bot):
bot.add_cog(Test(bot))

Nextcord Ban & Kick issue

I'm trying to make a discord.py bot with the help of nextcord and i've come far enough to make the code work in theory but nothing happens when i try to kick / ban, it just throws an
nextcord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Context' object has no attribute 'ban'
and i have no idea why it does so, i want it to work as inteded.
Note, the command(s) are class commands so the main bot loads in the command from another file.
Main Bot Script
# import nextcord
from nextcord.ext import commands
# import asyncio
import json
# Import all of the commands
from cogs.ban import ban
from cogs.hello import hello
from cogs.help import help
from cogs.info import info
from cogs.kick import kick
from cogs.test import test
#Define bot prefix and also remove the help command built in.
bot = commands.Bot(command_prefix=json.load(open("config.json"))["prefix"])
bot.remove_command("help")
#bot.event
async def on_ready():
print(f'Logged in as {bot.user}')
bot.add_cog(hello(bot))
bot.add_cog(help(bot))
bot.add_cog(info(bot))
bot.add_cog(test(bot))
bot.add_cog(ban(bot))
bot.add_cog(kick(bot))
bot.run(json.load(open("config.json"))["token"])
Problematic command
import discord
from nextcord.ext import commands
from nextcord.ext.commands import has_permissions, CheckFailure
bot = commands.bot
class ban(commands.Cog):
def __init__(self, client):
self.client = client
self._last_member = None
#commands.Cog.listener()
async def on_ready(self):
print('ban Cog Ready')
#commands.command()
#has_permissions(ban_members=True)
async def ban(ctx, user: discord.Member = None, *, Reason = None):
if user == None:
await ctx.send("Could you please enter a valid user?")
return
try:
await user.ban(reason=Reason)
await ctx.send(f'**{0}** has been banned.'.format(str(user)))
except Exception as error:
if isinstance(error, CheckFailure):
await ctx.send("Looks like you don't have the permissions to use this command.")
else:
await ctx.send(error)
You are doing:
user: discord.Member
You need to use nextcord instead.
user: nextcord.Member
#commands.command()
#has_permissions(ban_members=True)
async def ban(ctx, user: nextcord.Member = None, *, Reason = None):#
#The rest of your code here
You can do the following
For Normal bot
#client.command(name="ban", aliases=["modbancmd"], description="Bans the mentioned user.")
#commands.has_permissions(ban_members=True)
async def ban(self, ctx, member: nextcord.Member, *, reason=None):
# Code for embed (optional)
await member.ban(reason=reason)
# (optional) await ctx.send(embed=banembed)
You can do the following
For Cogs
#commands.command(name="ban", aliases=["modbancmd"], description="Bans the mentioned user.")
#commands.has_permissions(ban_members=True)
async def ban(self, ctx, member: nextcord.Member, *, reason=None):
# Code for embed (optional)
await member.ban(reason=reason)
# (optional) await ctx.send(embed=banembed)
Well, here are the problems:
Your command is in a cog therefore you need to say (self, ctx, and so on)
You need to change the discord to nextcord
You should change the commands.bot to commands.Bot()
And if I'm correct, you should change the self.client to self.bot since your commands.Bot() is defined as bot
And uhh yeah it should work perfectly after you fix those.

'NoneType object has no attribute ' send'

My code is returning this error NoneType object has no attribute 'send'
here is my code
import discord
import os
from discord.ext import commands
client = discord.Client()
class Logging(commands.Cog):
"""Sets up logging for you guild"""
def __init__(self, client):
self.bot = client
async def __error(self, ctx, error):
if isinstance(error, commands.BadArgument):
await ctx.send(error)
#commands.Cog.listener()
async def on_message_delete(self, message,):
deleted = embed = discord.Embed(
description=f"Message deleted in {message.channel.mention}", color=0x4040EC
).set_author(name=message.author, url= discord.Embed.Empty, icon_url=message.author.avatar_url)
channel = client.get_channel(888600482317213786)
deleted.add_field(name="Message", value=message.content)
deleted.timestamp = message.created_at
await channel.send(embed=deleted)
def setup(client):
client.add_cog(Logging(client))
I am doing this in my cogs and not in the main.py
channel = client.get_channel(888600482317213786) should be channel = self.bot.get_channel(888600482317213786). Then check if channel is None.
I assume there is no indentation error in your actual code.

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

python3 aiogram. How to send message to user_id

from aiogram import Bot
import config
def send_message(message):
operator = Bot(config.operator_token)
operator.send_message(config.user_id, message)
def main():
send_message('hi')
I want to send message to user with id from my config.py (config.user_id). But it's not workinkg. I tried many ways for it but I always got an error.
For example like this
Unclosed client session
client_session: <aiohttp.client.ClientSession object at 0x7f94a9b62550>
Unclosed connector
connections: ['[(<aiohttp.client_proto.ResponseHandler object at 0x7f94a98f8040>,
23065.38)]']
connector: <aiohttp.connector.TCPConnector object at 0x7f94a9b3c400>'
If you use aiogram you must use async/await to send message.
bot = Bot(token=TOKEN)
dp = Dispatcher(bot_init)
#dp.message_handler(commands=['test'])
async def process_start_command(message: types.Message):
await bot.send_message(message.from_user.id, "test message") #like this
#await message.answer("test message")
#or like this
Maybe this?!
import asyncio
from aiogram import Bot
import config
async def send_message(message):
operator = Bot(config.operator_token)
await operator.send_message(config.user_id, message)
def main():
asyncio.run(send_message('hi'))
from aiogram import Bot, types
from aiogram.dispatcher import Dispatcher
from aiogram.utils import executor
from config import TOKEN
bot = Bot(token=TOKEN)
dp = Dispatcher(bot)
#dp.message_handler(commands=['start'])
async def process_start_command(message: types.Message):
await message.reply("Hello\nWrite me something!")
#dp.message_handler(commands=['help'])
async def process_help_command(message: types.Message):
await message.reply("Implementation EchoBot")
#dp.message_handler()
async def echo_message(msg: types.Message):
await bot.send_message(msg.from_user.id, msg.text)
if __name__ == '__main__':
executor.start_polling(dp)

Resources