how can send photo to user with pyTelegrambotapi - python

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))

Related

AttributeError in MessageFwdHeader telethon library

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.

'Context' object has no attribute 'reddit' Discord.PY

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.

Running slack bot with python issue - AttributeError: 'WebClient' object has no attribute 'rtm_read'

I am following this guide:
At the very end there is a full code snippet which I took, but there is a problem with the last part of it:
if __name__ == "__main__":
if slack_client.rtm_connect(token = slack_token):
print("Starter Bot connected and running!")
# Read bot's user ID by calling Web API method `auth.test`
starterbot_id = slack_client.api_call("auth.test")["user_id"]
while True:
command, channel = parse_bot_commands(slack_client.rtm_read())
if command:
handle_command(command, channel)
time.sleep(RTM_READ_DELAY)
else:
print("Connection failed. Exception traceback printed above.")
I am getting
Starter Bot connected and running!
Traceback (most recent call last):
File "slack2.py", line 67, in <module>
command, channel = parse_bot_commands(slack_client.rtm_read())
AttributeError: 'WebClient' object has no attribute 'rtm_read'
I've tried reinstalling and instaling slack client as suggested in the first 5 google searches but still having the same issue. My slackclient==2.5.0 and my slack_client = slack.WebClient(token=slack_token).
Any ideas where does the problem lie? Thank you for your suggestions.

Python - Error in authorized client request

Create an "authorized_token" Token object and use that to perform Twitter API calls on behalf of user
authorized_token = oauth2.Token(access_token['oauth_token'], access_token['oauth_token_secret'])
authorized_client = oauth2.Client(consumer, authorized_token)
Make Twitter API calls!
response, content = authorized_client.request('https://api.twitter.com/1.1/search/tweets.json?q=computers+filter:images', 'GET')
if response.status != 200:
print("An error occurred when searching!")
print(content.decode('utf-8'))
Error -
Exception has occurred: AttributeError 'list' object has no attribute
'encode'
The error indicates the following code
response, content = authorized_client.request('https://api.twitter.com/1.1/search/tweets.json?q=computers+filter:images', 'GET')
Someone can explain to me why?

Python Telegram bot - KeyError after running for a few hours

I wrote a Telegram bot in Python, which is running on my Raspberry Pi (Raspbian). I eventually see an error after the bot has been running for a few hours.
Before I post the complete code, could someone please help me understand the error? I would like to run the bot indefinitely, or at least for multiple days, before I need to restart it.
The error is as follows:
Traceback (most recent call last):
File "/home/pi/Schreibtisch/StreamrPreisBot/telepot/loop.py", line 37, in run_forever
self._handle(msg)
File "/home/pi/Schreibtisch/StreamrPreisBot/streamrinfobot.py", line 32, in handle
command = msg['text']
KeyError: 'text'
Edit:
Following code is used:
def handle(msg):
chat_id = msg['chat']['id']
command = msg['text']
Might this code solve the problem?
def handle(msg):
chat_id = msg['chat']['id']
command = msg.get('text')
Error says there is no text key inside msg dict. Maybe it's some special telegram message that has no text or there is a bug in you code that delete text key in some cases. You could use
command = msg.get('text')
To get None when there is no text. Or
command = msg.get('text', '')
To get empty string (i.e. '') when there is no text.
You could also check that there is a text inside msg or not with in operator:
if 'text' not in msg:
logger.error('bad message received!')
return
If you want to your service to be always up you should add some mechanism for automatic restart.
like in Python to restart after any error:
while True:
try:
logger.info("Starting bot")
run_bot()
except Exception:
logger.exception("Something bad happened. Restarting")
I also suggest to log errors in a file or services such as Sentry to investigate why there is no text afterwards.
A KeyError is raised when a value is requested from a dict but the key does not exist in the dictionary.
So, in your case, the msg dictionary does not have the key text.
You should inspect your code to ensure that the msg dictionary contains a value associated with the key text. Or, if you expect that msg will sometimes not contain the key text, you should instead access the dictionary with the get method, which never raises a KeyError. See the docs for more information.

Categories

Resources