How to reply a massage in Telepot? - telegram

I am making a telegram bot with telepot , but I don't know how to do it. I tried many solutions, but I didn't get an answer and the bot only sent simple messages without reply!
My source is supposed to run on the pythoneverywhere site, so I have the limitation of using other libraries like telethon.
here is my code :
import telepot
import urllib3
import random, time
proxy_url = "http://proxy.server:3128"
telepot.api._pools = {
'default': urllib3.ProxyManager(proxy_url=proxy_url, num_pools=3, maxsize=10, retries=False, timeout=30),
}
telepot.api._onetime_pool_spec = (urllib3.ProxyManager, dict(proxy_url=proxy_url, num_pools=1, maxsize=1, retries=False, timeout=30))
bot = telepot.Bot('')
def handle(msg):
content_type, chat_type, chat_id .= telepot.glance(msg)
massage = msg["text"]
bot.sendMessage(chat_id, text="Reply From Bot!" ,reply_to_message_id=massage)
bot.message_loop(handle)
print('RUNNING!')
while 1:
time.sleep(10)
I tried :
bot.sendMessage(chat_id, text="Reply From Bot!" ,reply_to_message_id=massage)
and I expected :
Reply From Bot!

Instead of using massage you can use msg['message_id']
def handle(msg):
content_type, chat_type, chat_id .= telepot.glance(msg)
massage = msg["text"]
bot.sendMessage(chat_id, text="Reply From Bot!" ,reply_to_message_id=msg['message_id'])
And also just mentioning; it seems like telepot is no longer maintained by developers as mentioned in telepot's GitHub repository. It would be better to switch into a library like python-telegram-bot

Related

Telegram Bot Python Inlinekeyboardmarkup does not work for all users in a group

I want to respond when someone sends the /start comand and display a text with a like/dislike button in a group.
Here is my sample code:
from telegram import InlineKeyboardButton, InlineKeyboardMarkup
from telegram.ext import (
Updater,
CommandHandler,
CallbackQueryHandler,
ConversationHandler)
import logging
FIRST, SECOND = range(2)
keyboard = [[InlineKeyboardButton('👍', callback_data='0'),
InlineKeyboardButton('👎', callback_data='2')]]
def start(update, context):
reply_markup = InlineKeyboardMarkup(keyboard)
update.message.reply_text(
'Test Message\n',
reply_markup=reply_markup
)
return FIRST
def main():
updater = Updater(
'TOKEN', use_context=True)
dp = updater.dispatcher
conv_handler = ConversationHandler(
entry_points=[CommandHandler('start', start)],
states={
FIRST: [CallbackQueryHandler(a, pattern='^'+str(0)+'$'),
CallbackQueryHandler(b, pattern='^'+str(2)+'$')]
},
fallbacks=[CommandHandler('start', start)]
)
dp.add_handler(conv_handler)
updater.start_polling()
updater.idle()
if __name__ == "__main__":
main()
The callbacks only work for the user who sent the /start command. Other users cannot click the button or there is no callback. if another user sends a /start command, both like/dislike buttons of both posts of the bot work for the two users.
Where is the mistake?
I want every user to be able to press the buttons and it triggers a callback. regardless of whether the user has ever sent the /start command
I am thankful for every help.
The issue here is that by default conversations are per user - please also see this faq entry for details.
For your use case, I doubt that a ConversationHandler gives you any benefit. I would just register the CommandHandler and the CallbackQueryHandler independently.
Disclaimer: I'm currently the maintainer of python-telegram-bot.

My Discord bot isn't responding to a command to pull data from timezonedb

So it can actually show the info I want it to in the terminal. But when I prompt it to send it as a discord message it appears to be attempting to send a blank message. It's probably something stupid, but thank you for looking. The language is Python.
import os
import discord
import requests
import json
import pprint
client = discord.Client()
def get_time():
response = requests.get("http://api.timezonedb.com/v2.1/get-time-zone?key=W9BJQ3QMGG69&format=json&by=position&lat=37.9838&lng=23.7275")
return pprint.pprint(response.json())
#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('$petertest'):
clock = get_time()
await message.channel.send(clock)
client.run(os.environ['TOKEN'])
You are using the pprint module to print the data to the console itself. That is the issue there
Changing your code to simply return the data will fix the error.
return response.json()
If you want to send the formatted json data to discord, you can use json.dumps:
if message.content.startswith('test'):
clock = get_time()
clock = json.dumps(clock, indent=4)
await message.channel.send(clock)

"403","message":"Feature level access has been denied"

I have a valid Here licence and I have been using it for long time. Suddenly I had the above response from server.
The url is: http://pde.api.here.com/2/matchroute.json?app_id=xxxxxxxxxxxxxxx&app_code=xxxxxxxxxxxx&routemode=car&file=&regions=WEU&release=LATEST
def connectPost(self, url, data, headers=None):
return self.S.post(url, data=data, headers=headers , proxies = self.proxy_dict)
As per the licensing, and delivery back-end system The account has expired that's why.
Cheers,
WaliedCheetos
Try please this python code(it works properly for me)
# Hello World program in Python
import requests
import json
data = bytes("\n".join([
'LATITUDE,LONGITUDE',
'50.875182,4.499943',
'50.875240,4.499935',
'50.875302,4.499920',
'50.875375,4.499893',
'50.875450,4.499854',
'50.875527,4.499799',
'50.875602,4.499728',
'50.875670,4.499643'
]), 'utf-8')
url = 'http://pde.api.here.com/2/matchroute.json?app_id=xxxx&app_code=xxxxx&routemode=car&regions=WEU&release=LATEST'
resp = requests.post(url, data)
parsed = json.loads(resp.text)
print(json.dumps(parsed, indent=4, sort_keys=True))
This code in on playground

Handle telegram webhook data in python 3

I made chatbot using this framework pyTelegramBotAPI and set webhook to my chatbot in Telegram. I use CherryPy for this. Everything works fine. But I can't handle data which user sends to my bot. I just get notification that user send something. How I can solve this? Thanks.
I solved this issue. Just found variable in my code that responds for json. Here's my code:
class WebhookServer(object):
#cherrypy.expose
def index(self):
if 'content-length' in cherrypy.request.headers and \
'content-type' in cherrypy.request.headers and \
cherrypy.request.headers['content-type'] == 'application/json':
length = int(cherrypy.request.headers['content-length'])
json_string = cherrypy.request.body.read(length).decode("utf-8") <-- this one responds for json from webhook
update = telebot.types.Update.de_json(json_string)
global jsonObj
jsonObj = json.loads(json_string)
print(jsonObj)
bot.process_new_updates([update])
return ''
else:
raise cherrypy.HTTPError(403)

How to get a Telegram Channel Id without sending a message to it

Is there any way to find a telegram channel id without sending a message to it ?
Right now I go this way and find the channel id by calling this URL in my code and get the JSON as result:
https://api.telegram.org/bot???????/sendMessage?chat_id=#?????&text=123
However, this cause sending the message "123" to the channel which is not good.
Check this link for help.
It is using web telegram url param info.
Adding details from the referred link:
log in web telegram
Click on the target channel then you will find the url displayed on your browser.
If it's a public channel, the ID is #name of the channel.
If it's a private channel then the url must be similar to:
https://web.telegram.org/#/im?p=c1018013852_555990343349619165
For this case, the channel ID would be 1018013852.
It's important to know that channel's IDs are always negative and 13 characters long!
So add -100 to it, making the correct ID -1001018013852.
You Can use Web Telegram to see each channel id in link of that page in your explorer
or
Just Simply Forward a message from your channel to This Bot: (https://telegram.me/getidsbot)
Yes, just forward a message of the channel to your bot and get the message.forward_from_chat.id.
Get your channel link
install python library telethon
get your api_id and api_hash here.
write the following code and run:
from telethon import TelegramClient
api_id=
api_hash=
channel_link = 'your_channel_link'
client = TelegramClient(session_name, api_id, api_hash,
update_workers=4, spawn_read_thread=False)
client.start()
entity = client.get_input_entity(**channel_link**)
print(entity.channel_id)
By the way, if you use it for telegram bot, just add -100 before the printed id, this should be work!
You Don't Need to get Channels ID .
simple send Message with Channel User Like : #channel
Fixing #scruel's answer:
In [1]: api_id = ...
In [2]: api_hash = '...'
In [3]: channelLink = 'https://t.me/BTCST_Community_EN'
In [4]: from telethon import TelegramClient, events
In [5]: client = TelegramClient('test', api_id, api_hash)
In [6]: client.start()
Out[6]: <telethon.client.telegramclient.TelegramClient at 0x7fc90c352290>
In [7]: entity = await client.get_entity(channelLink)
In [8]: channelId = '-100' + str(entity.id)
In [9]: channelId
Out[9]: '-1001236496320'
Here's a CLI util to do it:
#!env/bin/python
import sys
import asyncio
from telethon import TelegramClient
import config
async def channel_id_from_link(client, channel_link):
return "-100" + str((await client.get_entity(channel_link)).id)
async def main(channel_link):
async with TelegramClient(
"test", config.api_id, config.api_hash
) as client:
channel_id = await channel_id_from_link(client, channel_link)
return channel_id
if __name__ == "__main__":
channel_link = sys.argv[1]
channel_id = asyncio.run(main(channel_link))
print(channel_id)
Test:
> ./TelegramChannelId.py https://t.me/binance_api_english
-1001134190352
Put your bot into your channel and go to https://api.telegram.org/bot/getUpdates.
If someone send message to that channel, you will get the channel ID there.

Resources