discord.py: show messages counter in a channel - python

I'm a complete beginner in discord.py, I create a bot and try to count all messages posted in a channel. The bot will show this counter in a message when I call it with the command "!bot".
It works with the simple example "ping" (send "pong" successfully), but when I send "!bot" it returns an error in console:
[2022-09-09 16:59:37] [ERROR ] discord.client: Ignoring exception in on_message
Traceback (most recent call last):
File "C:\Users\Rinnosuke\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\client.py", line 409, in _run_event
await coro(*args, **kwargs)
File "D:\Programmation\Python\Discord-bot\bot4.py", line 29, in on_message
message_count()
TypeError: __call__() missing 1 required positional argument: 'context'
This is my code, what arguments should I pass to the message_count function call?
import discord
from discord.ext import commands
intents = discord.Intents.default()
intents.message_content = True
client = discord.Client(intents=intents)
prefix = "!b"
needed_intents = discord.Intents.default()
bot = commands.Bot(command_prefix=prefix, intents=needed_intents)
#client.event
async def on_ready():
print(f'We have logged in as {client.user}')
#client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.lower() == "ping":
await message.channel.send('pong')
if "!bot" in message.content:
message_count()
#bot.command()
async def message_count(ctx, channel: discord.TextChannel=None):
channel = bot.get_channel(586577242910359564)
count = 0
async for _ in channel.history(limit=None):
count += 1
await message.channel.send("There were {} messages in {}".format(count, channel.mention))
client.run('my token')
bot.run('my token')
Thanks!

You can't include this channel: discord.TextChannel=None You can either set its type or set its value, not both.

Related

I Cannot Run My Discord Bot Code Using Discord Library

import discord
client = discord.Client()
#client.event
async def on_member_join(member):
# Send a message to the welcome channel
welcome_channel = member.guild.get_channel(CHANNEL_ID)
await welcome_channel.send(f"Welcome {member.mention} to the server!")
client.run(TOKEN)
Whenever I Try Running This Code Replacing The Token And The Channel ID It Shows Me A Error Like:
Traceback (most recent call last):
File "main.py", line 3, in <module>
client = discord.Client()
TypeError: __init__() missing 1 required keyword-only argument: 'intents'

KeyboardInterrupt

As per the quickstart documentation (and the error message), you need to specify the intents you want to use.
Here's an example using the default intents.
import discord
intents = discord.Intents.default()
client = discord.Client(intents=intents)
#client.event
async def on_member_join(member):
# Send a message to the welcome channel
welcome_channel = member.guild.get_channel(CHANNEL_ID)
await welcome_channel.send(f"Welcome {member.mention} to the server!")
client.run(TOKEN)

error with discord.py NoneType object has no attribute 'id'

Ok, so I try to make a command with on_message, I put await bot.process_commands(message). But it always raises the 'NoneType' object has no attribute 'id'.
import os
import random
import discord
from discord.ext import commands
from dotenv import load_dotenv
load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')
intents = discord.Intents.default()
intents.message_content = True
activity = discord.Activity(name='null, dying, trying to fix me', type=discord.ActivityType.watching)
client = discord.Client(intents=intents, activity = activity)
bot = commands.Bot(intents=intents,command_prefix='!')
#client.event
async def on_ready():
print(f'{client.user.name} has connected to Discord!')
channel = client.get_channel(956302622170701946)
await channel.send(f'connected successfully as {client.user.name}#{client.user.discriminator}')
#client.event
async def on_message(message):
await bot.process_commands(message)
if message.author == client.user:
return
if message.content.startswith('hello'):
await message.channel.send("hello stopid")
elif message.content.startswith('die'):
await message.channel.send('ok :sob: i ded now')
await client.close()
#bot.command
async def a(ctx):
await ctx.send("a")
client.run(TOKEN)
this is the entire error:
2022-12-08 18:15:54 ERROR discord.client Ignoring exception in on_message
Traceback (most recent call last):
File "C:\Users\xxxxx\source\repos\DBot\DiscordBot\lib\site-packages\discord\client.py", line 409, in _run_event
await coro(*args, **kwargs)
File "c:\Users\xxxxx\source\repos\DBot\discordbot.py", line 25, in on_message
await bot.process_commands(message)
File "C:\Users\xxxxx\source\repos\DBot\DiscordBot\lib\site-packages\discord\ext\commands\bot.py", line 1389, in process_commands
ctx = await self.get_context(message)
File "C:\Users\xxxxx\source\repos\DBot\DiscordBot\lib\site-packages\discord\ext\commands\bot.py", line 1285, in get_context
if origin.author.id == self.user.id: # type: ignore
AttributeError: 'NoneType' object has no attribute 'id'
i just want a command with the prefix '$' and sends back the args sent by the user
i probably did something stupid but still thanks.
You only need the bot instance, client is unnecessary. CommandsBot is just upgraded discord.Client and also includes the #bot.event decorator
remove client.close() and move bot.process_commands(message) to the bottom of your on_message function
*Note you should not be doing anything else than prints in on_ready since that fires multiple times

How can I ignore the ctx argument from discord.py?

Here is the full script:
from discord.ext.commands import Bot
import tracemalloc
tracemalloc.start()
client = Bot(command_prefix='$')
TOKEN = ''
#client.event
async def on_ready():
print(f'Bot connected as {client.user}')
#client.command(pass_context=True)
async def yt(ctx, url):
author = ctx.message.author
voice_channel = author.voice_channel
vc = await client.join_voice_channel(voice_channel)
player = await vc.create_ytdl_player(url)
player.start()
#client.event
async def on_message(message):
if message.content == 'play':
await yt("youtubeurl")
client.run(TOKEN)
When I run this script, it works fine. When I type play in the chat, I get this error:
Traceback (most recent call last):
File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "C:\Users\user\bot.py", line 26, in on_message
await yt("youtubeurl")
File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 374, in __call__
return await self.callback(*args, **kwargs)
TypeError: yt() missing 1 required positional argument: 'url'
How do I fix this? So far all I have tried is added the argument * between ctx and url, which didn't fix it
It is not possible to "ignore" the context argument, why are you invoking the command in the on_message event?
You can get the context with Bot.get_context
#client.event
async def on_message(message):
ctx = await client.get_context(message)
if message.content == 'play':
yt(ctx, "url")
I'm guessing your commands aren't working cause you didn't add process_commands at the end of the on_message event
#client.event
async def on_message(message):
# ... PS: Don't add the if statements for the commands, it's useless
await client.process_commands(message)
Every command should be working from now on.
Reference:
Bot.get_context
Bot.process_commands

Discord API. exception error on on_member_remove()

import discord
from discord.ext import commands
intents = discord.Intents(
messages = True,
guilds = True, reactions = True,
members = True, presences = True
)
bot = commands.Bot(command_prefix = "[", intents = intents)
#bot.event
async def on_ready():
print("Bot ready")
#bot.event
async def on_member_join(member):
print(f"{member} is ___")
#bot.event
async def on_member_remove():
print("xxx")
if member.id == 341212492212600832:
invitelink = discord.TextChannel.create_invite(max_uses=1,unique=True)
await member.send(f"you ___ bro. Here u go {inviteLink}")
bot.run("TOKEN")
Ignoring exception in on_member_remove
Traceback (most recent call last):
File "C:\Users\Filbert\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
TypeError: on_member_remove() takes 0 positional arguments but 1 was given
As the error said, on_member_remove takes 1 positional argument member
#bot.event
async def on_member_remove(member): # You forgot to pass it
# ...
Reference:
on_member_remove
Similar to on_member_join, on_member_remove gets passed member, as said in the docs. After fixing this issue, regenerate your token, as you included it in the original post.
Another issue: You shouldn't be creating an instance of discord.TextChannel. Instead, get that channel using bot.get_channel(id), and call create_invite on the TextChannel instance that get_channel returns.

How to add role to person after saying smth

from discord.ext import commands
from discord.utils import get
client = discord.Client()
ROLE = 'SPECIAL'
BOT_PREFIX = '/'
bot = commands.Bot(command_prefix=BOT_PREFIX)
#client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
#client.event
async def on_message(message, member):
if message.author == client.user:
return
if message.author.name == "Pawlu_il_Fenku":
await message.channel.send('Hello!')
role = get(member.guild.roles, name=ROLE)
await member.add_roles(role)
print(f"{member} was given {role}")
client.run('NzY0MjA1MzA1MjQwMjIzNzQ0.X4C3pw.5RmXn1XswHCTWwOQ5i1v5lH5B6I')
when i run it and type something it gives me this:
Ignoring exception in on_message
Traceback (most recent call last):
File "C:\Users\jpbay\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\client.py", line 333, in _run_event
await coro(*args, **kwargs)
TypeError: on_message() missing 1 required positional argument: 'member'
any help?
on_message event has only 1 argument, which is message. You cannot use 2 parameters in this event but you can access every attribute that member object has with using message.author.
Also, I don't recommend you to use discord.Client and discord.Bot at the same time. discord.Bot can do everything that discord.Client does.
ROLE = 'SPECIAL'
BOT_PREFIX = '/'
client = commands.Bot(command_prefix=BOT_PREFIX)
#client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
#client.event
async def on_message(message, member):
if message.author == client.user:
return
if message.author.name == "Pawlu_il_Fenku":
await message.channel.send('Hello!')
role = get(message.guild.roles, name=ROLE)
await message.author.add_roles(role)
print(f"{message.author} was given {role}")
client.run('TOKEN')
NOTE:
You should change your token if you haven't changed yet.

Categories