Getting message content with Discord.py - python

I would like to have a command like $status idle and it would do the follow
variblething = 'I am idle'
activity = discord.Game(name=variblething)
await client.change_presence(status=discord.Status.idle, activity=activity)
then they can do $message write what you want the status to be
then it would change what the activity message is. I hope this all makes sense. My current code is the following
import discord
client = discord.Client()
#client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
#client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('$helloThere'):
await message.channel.send('General Kenobi')

Firstly I would highly advise that you use prefixes and the command decorators/functions.
This means that your on_message() function won't be a mile long. To set your bot's command prefix, you can do:
from discord.ext import commands
bot = commands.Bot(command_prefix ='$')
This will allow you to make commands like so:
#bot.command()
async def changeStatus(ctx, *, status):
if status == 'online':
new_status = discord.Status.online
elif status == 'offline':
new_status = discord.Status.offline
elif status == 'idle':
new_status = discord.Status.idle
elif status == 'dnd':
new_status = discord.Status.dnd
else:
return
await bot.change_presence(status=new_status, activity=discord.Game(f'I am {status}'))

Related

My code Wont run any line other than the bottom line of code

I was using the program fine and the bot and commands all worked as intended however after restarting the program only the code at the bottom would work, i.e if I deleted the slap section the punch would work but no other section.
If I deleted the punch section after that the help would work but no other section apart from that.
Here is my code:
# installed: discord api
import discord
import random
from datetime import date
from discord.ext import commands
from discord.embeds import Embed
from discord import colour
TOKEN = '***********'
intents = discord.Intents.all()
intents.message_content = True
client = discord.Client(intents=intents)
bot = commands.Bot(command_prefix='!', intents=intents)
#client.event
async def on_ready():
print(f"Bot logged in as {client.user}")
#client.event
async def on_message(message):
# greeting the bot
if message.author != client.user:
if message.content.lower().startswith('!hello'):
await message.channel.send(f"Wassup, `{message.author}`")
# help command which states all available bot commands
if message.author != client.user:
if message.content.lower().startswith('!help'):
await message.channel.send(f"`{message.author}` \nHere are all my commands:\n \n!hello ~ greet the bot \n"
f"!roll ~ the bot will give a random value between 1 and 100 \n"
f"!day ~ the bot will give the date and time \n"
f"!punch ~ the bot will send a punching gif ( not nsfw )\n"
f"!slap ~ the bot will send a slapping gif\n"
f"")
# roll command which returns a random value between 1 and 100
if message.author != client.user:
if message.content.lower().startswith('!roll'):
number = str(random.randint(1, 100))
await message.channel.send('Your number is: ' + number)
# day command which returns the date and time of the local system
if message.author != client.user:
if message.content.lower().startswith('!day'):
today = date.today()
await message.channel.send(f"The local date today is {today}")
# gif command which sends a punching gif to a tagged person
#client.event
async def on_message(message):
if message.author != client.user:
if message.content.lower().startswith('!punch'):
punch_gifs = ['https://media.tenor.com/6Cp5tiRwh-YAAAAC/meme-memes.gif']
punch_names = ['Punched You']
embed = discord.Embed(
colour=(discord.Colour.random()),
description=f'{message.author.mention} {random.choice(punch_names)}'
)
embed.set_image(url=(random.choice(punch_gifs)))
await message.channel.send(embed=embed)
# gif command which sends a slapping gif to a specified person
#client.event
async def on_message(message):
if message.author != client.user:
if message.content.lower().startswith('!slap'):
slap_gifs = ['https://media.tenor.com/mNAs5CO1deIAAAAC/slap.gif']
slap_names = ['slapped you']
embed = discord.Embed(
colour=(discord.Colour.random()),
description=f'{message.author.mention} {random.choice(slap_names)}'
)
embed.set_image(url=(random.choice(slap_gifs)))
await message.channel.send(embed=embed)
client.run(TOKEN)
I tried retyping the code and attempting to change certain code functions to avoid this but to no available.
You have multiple functions named on_message, so Python doesn't know which one to call. Just put each command in its own function, then you can stack elif statements in your on_message.
# installed: discord api
import discord
import random
from datetime import date
from discord.ext import commands
from discord.embeds import Embed
from discord import colour
TOKEN = 'TOKEN'
intents = discord.Intents.all()
intents.message_content = True
client = discord.Client(intents=intents)
bot = commands.Bot(command_prefix='!', intents=intents)
#client.event
async def on_ready():
print(f"Bot logged in as {client.user}")
# greeting the bot
async def hello_cmd(message):
await message.channel.send(f"Wassup, `{message.author}`")
async def help_cmd(message):
await message.channel.send(f"`{message.author}` \nHere are all my commands:\n \n!hello ~ greet the bot \n"
f"!roll ~ the bot will give a random value between 1 and 100 \n"
f"!day ~ the bot will give the date and time \n"
f"!punch ~ the bot will send a punching gif ( not nsfw )\n"
f"!slap ~ the bot will send a slapping gif\n"
f"")
async def roll_cmd(message):
# roll command which returns a random value between 1 and 100
number = str(random.randint(1, 100))
await message.channel.send('Your number is: ' + number)
# day command which returns the date and time of the local system
async def day_cmd(message):
today = date.today()
await message.channel.send(f"The local date today is {today}")
# gif command which sends a punching gif to a tagged person
async def punch_cmd(message):
punch_gifs = ['https://media.tenor.com/6Cp5tiRwh-YAAAAC/meme-memes.gif']
punch_names = ['Punched You']
embed = discord.Embed(
colour=(discord.Colour.random()),
description=f'{message.author.mention} {random.choice(punch_names)}'
)
embed.set_image(url=(random.choice(punch_gifs)))
await message.channel.send(embed=embed)
# gif command which sends a slapping gif to a specified person
async def slap_cmd(message):
slap_gifs = ['https://media.tenor.com/mNAs5CO1deIAAAAC/slap.gif']
slap_names = ['slapped you']
embed = discord.Embed(
colour=(discord.Colour.random()),
description=f'{message.author.mention} {random.choice(slap_names)}'
)
embed.set_image(url=(random.choice(slap_gifs)))
await message.channel.send(embed=embed)
#client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.lower().startswith('!slap'):
await slap_cmd(message)
elif message.content.lower().startswith('!punch'):
await punch_cmd(message)
elif message.content.lower().startswith('!roll'):
await roll_cmd(message)
elif message.content.lower().startswith('!hello'):
await hello_cmd(message)
elif message.content.lower().startswith('!day'):
await day_cmd(message)
elif message.content.lower().startswith('!help'):
await help_cmd(message)
client.run(TOKEN)

Discord Bot : 'Message' object has no attribute 'channell'

I have created a Discord bot with a Python script. This is a simple Discord bot where users can interact with it via specific messages. For example: when the user types "roll", the bot will roll the dice and give a random number.
main.py
import bot
if __name__ == '__main__':
bot.run_discord_bot()
bot.py
import discord
import responses
async def send_message(message, user_message, is_private):
try:
response = responses.get_response(user_message) # Need to be implemented
await message.author.send(response) if is_private else await message.channell.send(response)
except Exception as e:
print(e)
def run_discord_bot():
TOKEN = ''
intents = discord.Intents.default()
intents.message_content = True
client = discord.Client(intents=intents)
#client.event
async def on_ready():
print(f'{client.user} is now running!')
#client.event
async def on_message(message):
if message.author == client.user:
return
username = str(message.author)
user_message = str(message.content)
channel = str(message.channel)
print(f'{username} said: "{user_message}" ({channel})')
if user_message[0] == '?':
user_message = user_message[1:]
await send_message(message, user_message, is_private=True)
else:
await send_message(message, user_message, is_private=False)
client.run(TOKEN)
responses.py
import random
def get_response(message: str) -> str:
p_message = message.lower()
if p_message == 'hello':
return 'Hey there!'
if p_message == 'roll':
return str(random.randint(1,9))
if p_message == '!help':
return '`This is a help message that you can asked for.`'
return 'I didn\'t understand what you wrote. Try typing "!help".'
When the user input a hello, the bot did not respond and the code terminal print out an error message: 'Message' object has no attribute 'channell'
What happen? and how to fix it?
You have a typo. It should be message.channel not message.channell

unknown discord.py glitch

Hello I was following a discord bot tutorial video step by step yet when i publish my code and try to respond to it, it would completly ignore me and I have no idea why it does this here is the whole code.
import discord
import random
TOKEN = 'is here'
client = discord.Client(intents=discord.Intents.default())
#client.event
async def on_ready():
print('we have logged in as {0.user}'.format(client))
#client.event
async def on_message(message):
username = str(message.author).split('#')[0]
user_message = str(message.content)
channel = str(message.channel.name)
print(f'{username}: {user_message} ({channel})')
if message.author == client.user:
return
if message.channel.name == 'bot':
if user_message.lower() == 'hello':
await message.channel.send(f'hello {username}!')
elif user_message.lower() == 'bye':
await message.channel.send(f'see you later {username}!')
return
elif user_message.lower() == '!random':
response = f'this is your random number: {random.randrange(50000)}'
await message.channel.send(response)
return
if user_message.lower() == '!anywhere':
await message.channel.send('this can be used anywhere!')
return
client.run(TOKEN)
Fixed it for you. Your client.run(token) was inside the last if statement so your bot would not have even started also you need to enable intents in your developer account otherwise the bot might not be able to read messages.
username = str(message.author).split('#')[0] is unnecessary when you can just use username = message.author.name
import discord
import random
import asyncio
intents = discord.Intents.default()
intents.messages = True
intents.guild_messages = True
intents.message_content = True
client = discord.Bot(intents=intents, messages = True, guild_messages = True, message_content = True)
#client.event
async def on_ready():
print('we have logged in as {0.user}'.format(client))
#client.event
async def on_message(message):
username = message.author.name
channel = str(message.channel.name)
if message.author == client.user:
return
if message.channel.name == 'bot':
if message.content.startswith('hello'):
await message.channel.send(f'hello {username}!')
if message.content.startswith('!anywhere'):
await message.channel.send('this can be used anywhere!')
return
client.run('token_here')

Deleting messages that start with certain prefix [discord.py]

I want my bot to delete all messages that are not starting with the prefix .. I wrote this code so far in discord.py but it keeps deleting all messages.
#Client.event
async def on_message(message):
if message.author.has_role("Bot"):
return
elif message.content.startswith('.'):
return
else:
await message.delete()
Thanks in advance
Try doing it like this:
#client.event
async def on_message(ctx):
if ctx.content.startswith('.'):
await client.process_commands(ctx)
return
for role in ctx.author.roles:
if role.name == 'Bot':
return
await ctx.delete()
I would do it like this:
#Client.event
async def on_message(message):
if message.content.startswith(".") == False:
message.channel.purge(limit=1)
else:
pass

Unsure How to set a number to a variable python and how to make the bot notice every message

import random
import asyncio
import aiohttp
import json
from discord import Game
from discord.ext.commands import Bot
import discord
TOKEN = 'Token'
client = discord.Client()
botnum = 0
#client.event
async def on_message(message):
# we do not want the bot to reply to itself
if message.author == client.user:
return
if message.content.startswith('PeriBot'):
msg = "I'm Busy! D:<".format(message)
await client.send_message(message.channel, msg)
if discord.message and botnum == 20
msg = "You Clods are so loud!".format(message)
await client.send_message(message.channel, msg)
set botnum == 0
else:
botnum + 1
#client.event
async def on_ready():
print('Online and Ready to Play!')
print(client.user.name)
print(client.user.id)
await client.change_presence(game=discord.Game(name="With Emotions"))
print('------')
client.run("Token")
I want it to say a message every 20 messages but I am unsure how. I have somthing named botnum and it is == 0 and if there isn't 20 botnum's then it adds 1 to the botnum. If there is 20 it says a msg. I want it to add 1 to botnum every msg.
I'm noticing a lot of syntax errors in your code, I've updated it below with what it should look like, and noted the changes with ### at the end of the line where it was modified. As for "make them notice every message" I'll need some clarification and then update my answer if this doesn't suit your needs. I think the code I just provided should update the botnum with 1 every time a message is sent that isn't PeriBot which should solve your problem.
import random
import asyncio
import aiohttp
import discord
import json
from discord import Game
from discord.ext.commands import Bot
TOKEN = 'Token'
client = discord.Client()
#client.event
async def on_ready():
print('Online and Ready to Play!')
print(client.user.name)
print(client.user.id)
await client.change_presence(game=discord.Game(name="With Emotions"))
print('------')
botnum = 0
#client.event
async def on_message(message):
# we do not want the bot to reply to itself
if message.author == client.user:
return
elif message.content.startswith('PeriBot'): ### Updated to elif which is more acceptable
msg = "I'm Busy! D:<".format(message)
await client.send_message(message.channel, msg)
elif discord.message and botnum == 20: ### forgot a ":" and Updated to elif which is more acceptable
msg = "You Clods are so loud!".format(message)
await client.send_message(message.channel, msg)
botnum = 0 ### you were comparing and not setting botnum to 0
else:
botnum += 1 ### This will add 1 to the preexisting number of botnum
client.run("Token")

Categories

Resources