I'm getting AttributeError in my code. How can I fix it please
from telethon import events
#client.on(events.NewMessage(func=lambda e: e.is_private))
async def _(event):
x = await event.get_reply_message()
if x is None:
return
send = event.raw_text
who = event.sender_id
if x.fwd_from:
user = x.fwd_from.sender_id.user_id
else:
return
Error:
Line 11: AttributeError: 'MessageFwdHeader' object has no attribute 'sender_id'
the AttributeError usually use a not existence attribute ,check the object Attribute.
According to this and this in the docs it is possible to get the original sender ID like: message.forward.sender_id. By the way the result will be None if the sender's profile was hidden or that was a channel repost.
Related
code:
bot = telebot.TeleBot("TOKEN", parse_mode=None)
#bot.message_handler(content_types=['photo'])
def handle_docs_photo(message):
bot.send_photo("1267203280",message.file_id)
error:
File "/home/Mrcpp1/test.py", line 23, in handle_docs_photo
bot.send_photo("1267203280",message.file_id)
AttributeError: 'Message' object has no attribute 'file_id'
I search about it bot can't find answer
and I tried different methods but can't solve it
how can solve it ?
Use send_photo:
try:
bot.send_photo(message.from_user.id, open("path_to_your_photo", 'rb'))
except Exception as error:
bot.send_message(message.from_user.id, str(error))
I'm trying to add a .reddit command to my bot. This is my code:
#client.command(name="random", aliases=["reddit"])
async def _random(ctx, subreddit: str = ""):
reddit = None
if reddit_app_id and reddit_app_secret:
reddit = praw.Reddit(client_id=reddit_app_id,client_secret=reddit_app_secret,user_agent="MASTERBOT:%s1.0" % reddit_app_id)
if reddit:
submissions = reddit.subreddit(subreddit).hot()
submission = next(x for x in submissions if not x.stickied)
await ctx.send(submissions.url)
I have everything imported, everything seemed fine until I got this error:
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Command' object has no attribute 'randint'
As I understood, the program has no idea what a randint is. I checked if I've made a typo, but no. Everything seemed fine. I was getting an antoher error on the same command but I managed to fix it. But this one got me and I need your help.
These are the new errors:
AttributeError: 'coroutine' object has no attribute 'url'
.
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
Do you have the command in a Cog (class)?
If you don't, then you should remove self, as it'll assume that that's the name of the context object.
#client.command(name="random", aliases=["reddit"])
async def _random( ctx, subreddit: str = ""):
reddit = None
if reddit_app_id and reddit_app_secret:
reddit = praw.Reddit(client_id=reddit_app_id,client_secret=reddit_app_secret,user_agent="MASTERBOT:%s1.0" % reddit_app_id)
if reddit:
chosen_subreddit = reddit_enabled_meme_subreddits[0]
if subreddit:
if subreddit in reddit_enabled_meme_subreddits:
chosen_subreddit = subreddit
submissions = reddit.subreddit(chosen_subreddit).hot()
post_to_pick = random.randint(1, 10)
for i in range(0, post_to_pick):
submission = next(x for x in submissions if not x.stickied)
await ctx.send(submission.url)
else:
await ctx.send("This is not working")
The issue is with the name of the command, random, as this is polluting the namespace of the random module. You're able to bypass this by renaming the command.
The async def random(.... is clashing with import random at the top of your code. You're able to set the name of the command with the name= keyword argument in the decorator. That's the name that people will be typing into discord.
Tried using your method of getting a random submission (minus the superfluous code, just the same logic), and it worked for me:
reddit = praw.Reddit(client_id="...", client_secret="...", user_agent="...")
#bot.command(name="reddit")
async def _reddit(ctx, subreddit: str = ""):
submissions = reddit.subreddit(subreddit).hot()
submission = next(x for x in submissions if not x.stickied)
await ctx.send(submission.url)
The only thing I can think of is making sure that you have the most up-to-date version of praw, and also if there's anything else in the command that you might be leaving out of the question, then that might be affecting it, although that's just speculation.
I'd say try making the command from the ground-up. Start off simple with something that works, and add to it line by line until something breaks. Then you'll know what's causing the RuntimeWarning and such.
Sorry for not having a clear-cut answer for this.
I am developing a Python app and using flask.
I am now writing my GET functions.
Here's how it should work:
GET http://{host_ip}:{port}/GetMessage?applicationId=1
GET http://{host_ip}:{port}/GetMessage?sessionId=aaaa
GET http://{host_ip}:{port}/GetMessage?messageId=bbbb
Here is my code:
#app.route('/GetMessage')
def GetMessage():
application_id = request.args.get('application_id')
messages = Message.query.filter_by(user_id=application_id)
return render_template('get.html', messages=messages)
#app.route('/GetMessage')
def GetMessage():
message_id = request.args.get('message_id')
messages = Message.query.filter_by(message_id=message_id)
return render_template('get.html', messages=messages)
But it sends me such an error message:
AssertionError: View function mapping is overwriting an existing endpoint function: GetMessage
what can be done?
Thanks!
def GetMessage():
messages = Message.query.all()
application_id = request.args.get('application_id')
if application_id:
messages.filter_by(user_id=application_id)
message_id = request.args.get('message_id')
if message_id:
messages = message.filter_by(message_id=message_id)
return render_template('get.html', messages=messages)
I am using pyTelegramBotApi and I would like to get the id of the message sent to a chat and then forward it to other chats the problem is that i always get this exception 'AsyncTask' object has no attribute 'message_id' while the message is sent correctly
how to solve?
bot = telebot.AsyncTeleBot(bot_token)
res = bot.send_message(cid,message)
try:
message_id = res.message_id
print(message_id)
except Exception as e:
print(e)
Since send_message() is an AsyncTask, you'll need to .wait() until the event is done;
res = bot.send_message(cid,message)
try:
result = res.wait()
print(result.message_id)
except Exception as e:
print(e)
More telegram-bot docs.
Sooo, I'm relatively new to programming, and trying to learn how to consume API's. I figured I would start out by building a Slack bot for moderation purposes since I use Slack a lot. For the most part, everything works except for when I try to delete a message. The API returns saying it can't find the message even though it is there in the channel (the slack API uses timestamps to locate said message). The timestamps match, but proclaims the message doesn't exist. Here is my code:
def __init__(self, token):
self.token = token
self.users = {}
self.channels = {}
self.slack = SlackClient(self.token)
self.as_user = True
def connect(self):
if self.slack.rtm_connect():
self.post_message('#test', "*AUTOMOD* _v0.1_")
while True:
# print(self.slack.rtm_read())
self.parse_data(self.slack.rtm_read())
time.sleep(1)
def parse_data(self, payload):
if payload:
if payload[0]['type'] == 'message':
print(("user: {} message: {} channel: {}").format(payload[0]['user'], payload[0]['text'], payload[0]['channel']))
self.handle_message(payload[0])
def handle_message(self, data):
# these users can post whatever they want.
WHITELISTED = ["U4DU2TS2F", "U3VSRJJD8", "U3WLZUTQE", "U3W1Q2ULT"]
# get userid
sent_from = (data['user'])
# ignore whitelisted
if sent_from in WHITELISTED:
return
# if message was sent from someone not in WHITELISTED, delete it
else:
print(("\n\ntimestamp of message: {}").format(data['ts']))
self.delete_message(data['channel'], data['ts'])
self.post_message(data['channel'], "```" + random.choice(dongers) + "```")
def delete_message(self, channel, timestamp):
print(("deleting message in channel '{}'...").format(channel))
print("timestamp check (just to make sure): ", timestamp)
deleted = self.slack.api_call("chat.delete",
channel=channel,
timestamp=timestamp,
as_user=self.as_user
)
if deleted.get('ok'):
print("\nsuccessfully deleted.\n")
else:
print(("\ncouldn't delete message: {}\n").format(deleted['error']))
OUTPUT
timestamp of message: 1488822718.000040
deleting message in channel: 'G4DGYCW2X'
timestamp check (just to make sure...): 1488822718.000040
couldn't delete message: message_not_found
Any ideas on what could be happening? Here is the chat.delete method for context.
EDIT:
Due #pvg's recommendation of "Minimal, Complete, and Verifiable example", I have placed the ENTIRE code from the project in a gist.
One issue might be that you appear to be passing a timestamp parameter to chat.delete, when the API method takes a ts parameter instead. (See docs)