tips:telegram

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revision Previous revision
Next revision
Previous revision
tips:telegram [2016/10/20 09:50] scipiotips:telegram [2022/04/12 08:07] (current) sscipioni
Line 1: Line 1:
 ====== Telegram ====== ====== Telegram ======
 +
 +{{tag>[telegram bot]}}
 +
 +===== channel =====
 +
 +send message to channel from bot (BOT_API_KEY required):
 +  - add bot to channel as admin
 +  - send message
 +
 +<code>
 +curl https://api.telegram.org/bot[BOT_API_KEY]/sendMessage?chat_id=@[MY_CHANNEL_NAME]&text=[MY_MESSAGE_TEXT]
 +</code>
 +
  
 ===== BOT ===== ===== BOT =====
 +
 +Create BOT with https://telegram.me/botfather
  
 <code> <code>
Line 7: Line 22:
 </code> </code>
  
-registrare un webhook+registrare un webhook (consigliato)
 <code> <code>
-pip install python-telegram-bot+pip install python-telegram-bot ipython
  
 ipython ipython
Line 42: Line 57:
  
 curl -F url="https://example.com:8443/<token>" -F certificate@=cert.pem  curl -F url="https://example.com:8443/<token>" -F certificate@=cert.pem 
 +</code>
  
 +==== Add BOT to group ====
 +
 +  * With BotFather click /setjoingroups, choose BOT
 +  * Add @BOT to group
 +  * Send a message to group
 +  * Give .result.message.chat.id from curl https://api.telegram.org/bot${TOKEN}/getUpdates (negative number)
 +<code bash>
 +TOKEN=
 +curl https://api.telegram.org/bot${TOKEN}/getUpdates | jq .
 </code> </code>
  
-===== Desktop Installer ===== 
  
 +Send a message to group
 <code bash> <code bash>
-#!/bin/bash +TOKEN
-  +CHATID
-echo "=============================================" +curl -X POST "https://api.telegram.org/bot${TOKEN}/sendMessage" -"chat_id=${CHATID}&text=my sample text
-echo "==     Telegram Script Installer v 0.1     ==" +</code>
-echo "==                                         ==" +
-echo "==            by Jalcaldea                 ==" +
-echo "=============================================" +
-  +
-echo "Downloading necesary files..." +
-  +
-cd /tmp +
-wget -O - https://tdesktop.com/linux > tsetup.tar.gz +
-wget -O - https://raw.githubusercontent.com/telegramdesktop/tdesktop/master/Telegram/Telegram/Images.xcassets/Icon.iconset/icon_256x256@2x.png > icon.png +
-  +
-echo "Making destination folder..." +
-  +
-sudo mkdir /usr/share/telegram +
-sudo chmod +x /usr/share/telegram +
-  +
-echo "Extracting files..." +
-  +
-tar -xvJf tsetup.tar.gz +
-cd ./Telegram +
-  +
-echo "Copying new files..." +
-sudo cp ./Updater /usr/share/telegram/Updater +
-sudo cp ./Telegram /usr/share/telegram/Telegram +
-user=$(whoami) +
-sudo chown -R $user:$user /usr/share/telegram/+
-  +
-echo "Making desktop files..." +
-  +
-cd /tmp +
-  +
-sudo echo "[Desktop Entry]" > telegram.desktop +
-sudo echo "Name=Telegram>> telegram.desktop +
-sudo echo "GenericName=Chat" >> telegram.desktop +
-sudo echo "Comment=Chat with yours friends" >> telegram.desktop +
-sudo echo "Exec=/usr/share/telegram/Telegram" >> telegram.desktop +
-sudo echo "Terminal=false" >> telegram.desktop +
-sudo echo "Type=Application" >> telegram.desktop +
-sudo echo "Icon=/usr/share/telegram/icon.png" >> telegram.desktop +
-sudo echo "Categories=Network;Chat;" >> telegram.desktop +
-sudo echo "StartupNotify=false" >> telegram.desktop +
-  +
-sudo cp icon.png /usr/share/telegram/icon.png +
-sudo cp telegram.desktop /usr/share/applications/telegram.desktop +
-  +
-echo "Removing old files..." +
-  +
-rm /tmp/tsetup.tar.gz +
-rm /tmp/icon.png +
-rm /tmp/telegram.desktop +
-rm -R /tmp/Telegram +
-  +
-  +
-echo "Installation Complete! Launching Telegram..." +
-  +
-/usr/share/telegram/Updater &+
  
 +To enable BOT to receive messages from group disable "group privacy" of BOT
 +
 +==== curl ====
 +
 +send message
 +<code bash>
 +#/bin/sh
 +
 +API="112212222:XXX..."
 +CHATID=123456
 +TEXT="$*"
 +
 +curl --data chat_id=$CHATID --data-urlencode "text=$TEXT"  "https://api.telegram.org/bot$API/sendMessage"
 </code> </code>
 +===== bot video =====
 +
 +<code python>
 +#!/usr/bin/env python3
 +# -*- coding: utf-8 -*-
 +"""Basic example for a bot that uses inline keyboards.
 +
 +# This program is dedicated to the public domain under the CC0 license.
 +"""
 +
 +TOKEN="xxx:xxx"
 +AUTHORIZED=[73496590,483703779,534914573,536325022]
 +
 +import logging
 +from telegram import InlineKeyboardButton, InlineKeyboardMarkup, ReplyKeyboardMarkup
 +from telegram.ext import Updater, CommandHandler, CallbackQueryHandler
 +import subprocess
 +
 +logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
 +                    level=logging.INFO)
 +logger = logging.getLogger(__name__)
 +
 +
 +def _isAuthorized(update):
 +    isOk = update.effective_user['id'] in AUTHORIZED
 +    if not isOk:
 +        update.message.reply_text('maybe another time, you are %s' % update.effective_user['id'])
 +    return isOk
 +        
 +        
 +def reply(update, message):
 +    reply_keyboard = [['/show', '/motion', '/day']]
 +    update.message.reply_text(message, reply_markup=ReplyKeyboardMarkup(reply_keyboard, resize_keyboard=True, one_time_keyboard=False))
 +    
 +
 +def start(bot, update):
 +    if _isAuthorized(update):
 +        reply(update, "welcome")
 +        #update.message.reply_text('comandi', reply_markup=ReplyKeyboardMarkup(reply_keyboard, resize_keyboard=True, one_time_keyboard=False))
 +
 +def show(bot, update):
 +    print("show ...")
 +    if _isAuthorized(update):
 +        user_id = update.effective_user['id']
 +        subprocess.call(["/home/pi/preview.sh", str(user_id)], shell=False)
 +        reply(update, 'recording ... wait 15 seconds ...')
 +
 +def motion(bot, update):
 +    print("show latest motion ...")
 +    if _isAuthorized(update):
 +        user_id = update.effective_user['id']
 +        reply(update, 'send latest motion video ...')
 +        subprocess.call(["/home/pi/latest.sh", str(user_id)], shell=False)
 +
 +def error(bot, update, error):
 +    """Log Errors caused by Updates."""
 +    logger.warning('Update "%s" caused error "%s"', update, error)
 +
 +
 +def previewday(bot, update):
 +    if _isAuthorized(update):
 +        user_id = update.effective_user['id']
 +        message = update.message['text'][1:].split(" ")
 +        camera = message[0]
 +        try:
 +            speed = int(message[1])
 +        except:
 +            speed = 50
 +        reply(update, 'send latest 24 hours from camera %s at speed %s, wait 5 minutes ...' % (camera, speed))
 +        makedayvideo(user_id, camera, speed=speed)
 +
 +
 +def makedayvideo(user_id, camera, speed=50):
 +        print(["/home/pi/preview-day.sh", str(user_id), camera, str(speed)])
 +        subprocess.call(["/home/pi/preview-day.sh", str(user_id), camera, str(speed)], shell=False)
 +
 +def button(bot, update):
 +    query = update.callback_query
 +    chat_id=query.message.chat_id
 +
 +    bot.edit_message_text(text='send latest 24 hours from camera %s at speed 50, wait 5 minutes ...'.format(query.data), chat_id=chat_id, message_id=query.message.message_id)
 +    makedayvideo(chat_id, query.data, speed=50)
 +
 +
 +def buttonpreview(bot, update):
 +    if _isAuthorized(update):
 +        keyboard = [[InlineKeyboardButton("1", callback_data='1'), 
 +            InlineKeyboardButton("2", callback_data='2'),
 +            InlineKeyboardButton("3", callback_data='3'),
 +            InlineKeyboardButton("4", callback_data='4'),
 +            InlineKeyboardButton("5", callback_data='5'),
 +            ]]
 +        reply_markup = InlineKeyboardMarkup(keyboard)
 +        update.message.reply_text('camera:', reply_markup=reply_markup)
 +
 +def main():
 +    updater = Updater(TOKEN)
 +
 +    updater.dispatcher.add_handler(CommandHandler('start', start))
 +    updater.dispatcher.add_handler(CommandHandler('show', show))
 +    updater.dispatcher.add_handler(CommandHandler('motion', motion))
 +    updater.dispatcher.add_handler(CommandHandler('1', previewday))
 +    updater.dispatcher.add_handler(CommandHandler('2', previewday))
 +    updater.dispatcher.add_handler(CommandHandler('3', previewday))
 +    updater.dispatcher.add_handler(CommandHandler('4', previewday))
 +    updater.dispatcher.add_handler(CommandHandler('5', previewday))
 +    updater.dispatcher.add_handler(CommandHandler('day', buttonpreview))
 +    updater.dispatcher.add_handler(CallbackQueryHandler(button))
 +    updater.dispatcher.add_error_handler(error)
 +
 +    updater.start_polling()
 +    updater.idle()
 +
 +
 +if __name__ == '__main__':
 +    main()
 +</code>
 +
 +
 +
  • tips/telegram.1476949831.txt.gz
  • Last modified: 2016/10/20 09:50
  • by scipio