Discord.py Message object is not subscriptable - python-3.x

I used channel.history() and trying now to print ID of the message or print the message, but I´m getting this error: TypeError: 'Message' object is not subscriptable. The problem is, when I´m not doing subscriptation, I get something like that:
<Message id=1044396942815412314 channel= type=<MessageType.default: 0> author= flags=>
How can I get the message or message ID from it to print it?
Thank you and sorry for my english.
This is code:
token = My token
import discord
import nest_asyncio
nest_asyncio.apply()
listus = []
listus2 = []
kanal = 1044396925635534848
intents = discord.Intents.default()
intents.message_content = True
client = discord.Client(intents=intents)
#client.event
async def on_ready():
channel = client.get_channel(kanal)
async for message in channel.history(limit=200):
if message.author:
print(message)
client.run(token)

Just use the id attribute of it (message.id)
Maybe I should tell you to read the documentation?
discord.py is one of the best documentated libraries in my opinion.
So I suggest you have a look on it: https://discordpy.readthedocs.io/en/stable/api.html

Related

Echo a message from another app in discord

I have a bot running in a separate app, but there is a specific variable holding data that I want to also be echo'd on my discord server. The bot itself is huge, but I can pin the specific method here
import discord
import asyncio
import rpChat
global note
class EchoBot(rpChat.ChatClient):
def on_PRI(self, character, message):
super().on_PRI(character, message)
note = character + ": " + message
global note
if message[:1] == "~":
super().PRI("A GameMaster", note)
to try to send this message to discord, I have the following. This is not put in the class above, but just below it, and is not in a class itself:
client = discord.Client()
async def discordEcho():
"""Background task that sends message sent from chat to an appropriate Discord channel
when global messege data is updated"""
await client.wait_until_ready()
channel = client.get_channel(serverroom}
while not client.is_closed():
global note
await channel.send(channel, note)
The data to grab the channel IDs are found in a json
file = open("credentials.json", "r", encoding="utf-8")
info = json.load(file)
file.close()
token = info["discord"]
serverroom = info["serverroom"]
client.loop.create_task(discordEcho())
client.run(token)
When I try this, I obtain:
await client.send_message(channel, message)
AttributeError: 'Client' object has no attribute 'send_message'
And I am unsure why. I have built a bot for both this chat platform, and for discord, but this is the first time I've ever attempted to bridge messages between the two. I am sure what I have offered is clear as mud, but any help would be appreciated, if possible.
Edit:
Edited changes to code. It is working thanks to comment below.
client.send_message is an old, outdated method, it has been replaced with Messageable.send
async def discordEcho():
"""Background task that sends message sent from chat to an appropriate Discord channel
when global messege data is updated"""
await client.wait_until_ready()
channel = client.get_channel(serverroom)
while not client.is_closed():
global note
await channel.send(note)
Side note: you first need to wait_until_ready before getting the channel to wait until the cache is done loading, otherwise channel will be None

Python3 + Discord - Send a message each X seconds

I am trying to create a Discord bot that would automatically send a message each X seconds (every 3 seconds, for example) without any user interaction/command input.
This is the code that I have:
import discord
from discord.ext import tasks, commands
bot = commands.Bot(command_prefix="!")
#bot.event
async def on_ready():
await bot.wait_until_ready()
print("Logged in as:")
print(bot.user.name)
print("------")
channel = bot.get_channel(IDasInteger)
print("Channel is:")
print(channel) #Prints None
get_price.start()
#tasks.loop(seconds=3)
async def get_price():
await bot.wait_until_ready()
channel = bot.get_channel(IDasInteger)
print("Channel is:")
print(channel) #Prints None
await channel.send('Test')
#get_price.before_loop
async def before ():
print("Before done.")
bot.run('MyTokenHere')
The problem is, that when I execute this code, it gives me the following error:
AttributeError: 'NoneType' object has no attribute 'send'
When I try to print the channel variable it returns None.
The Channel ID is correct - I have copied it directly from Discord app without any alterations to its value.
Any ideas, please?
Thank you
The reason you are getting None is that IDasInteger is not defined (at least in the code you provided. If it is defined in your code then it cannot find the channel and returns None. None does not have the attribute send and the error is raised.
Change the channel id to the id of a valid channel in your server.
functions channel = bot.get_channel(790279425633758682)
Or make sure the IDasInteger is returning a valid channel ID
Note: I tested the code with a valid channel id to my server and it worked as intended.

on_member_join can't print a message

I'm doing a Discord bot with Python 3.8 and I have a problem with my event on_member_join().
#bot.event
async def on_member_join(member):
embed = discord.Embed(
title=f"that doesn't function")
channel = discord.utils.get(member.guild.channels, name='WELCOME_CHANNEL_NAME')
await member.send('Hello')
await channel.send(embed=embed)
member.send sends a private message with hello but channel.send sends this error await channel.send(embed=embed) AttributeError: 'NoneType' object has no attribute 'send'
I really don't know how to do,
Thanks for your help!
Because you probably don't have a channel named WELCOME_CHANNEL_NAME. That's why channel returns None. You need to type the real welcome channel name instead of WELCOME_CHANNEL_NAME in channel = discord.utils.get(member.guild.channels, name='WELCOME_CHANNEL_NAME').

How do I add a reaction emoji to the message the bot sends after doing the user's command?

I get this error: discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Bot' object has no attribute 'message'--when trying to do await self.client.message.add_reaction(emoji).
I tried changing it to await ctx.message.add_reaction(emoji), and I realized that it reacted to the command the user sent rather than the bot's new message.
import discord
from discord.ext import commands
class MovieNight(commands.Cog):
"""Polls for Movie Night."""
def __init__(self, client):
self.client = client
#commands.command(aliases=['m'])
async def movie(self, ctx, year, *movie):
movie_title = ' '.join(movie[:-1])
await ctx.send(f"`{year}` - `{movie_title}` | **{movie[-1]}**")
emoji = '👎'
await self.client.message.add_reaction(emoji)
def setup(client):
client.add_cog(MovieNight(client))
self.client doesn't know about the message, the is stored as part of the invocation context:
await ctx.message.add_reaction(emoji)
Adding onto Patrick's answer here from what you said in the comment.
await self.client.message.add_reaction(emoji) won't work because the bot doesn't know what message you're referring to, and client doesn't have an attribute called message.
Adding reactions requires a discord.Message object, which in your case can be either the command that the user executed (e.g. !movie 2020 movie title) which you can retrieve via ctx.message, or a message which you're making the bot send.
If you wanted to get the message object from the message that the bot sent, you can assign it to a variable:
msg = await ctx.send(f"`{year}` - `{movie_title}` | **{movie[-1]}**")
And this allows you to then add a reaction to it or access any other message attributes you would like:
emoji = '👎'
await msg.add_reaction(emoji)
References:
discord.Message
Message.add_reaction()
TextChannel.send() - Here you can see it returns the message that was sent

AttributeError: 'Client' object has no attribute 'command'

I have added this code:
#client.command(pass_context=True)
async def name(ctx):
username = ctx.message.author.display_name
On to the end of my line of code, and I get this error when trying to get the bot online:
AttributeError: 'Client' object has no attribute 'command'
You need to use discord.ext.commands.Bot instead of discord.Client. Bot is a subclass of Client, so you can also use all of the Client functionality with a Bot instance
from discord.ext.commands import Bot
bot = Bot("!")
#bot.command()
async def test(ctx):
await ctx.send("Command executed")
await bot.run("TOKEN")
client = discord.Client(intents=intents )
Check this :)
client=commands.Bot(command_prefix=".")
This resolves my isssue :)

Resources