Skip to content

Instantly share code, notes, and snippets.

@ly0
Last active December 11, 2017 04:02
Show Gist options
  • Save ly0/e836767a63b57204533852327a086d30 to your computer and use it in GitHub Desktop.
Save ly0/e836767a63b57204533852327a086d30 to your computer and use it in GitHub Desktop.
Simplify notification with less than 30 lines in telegram way
import aiohttp
from aiohttp import web
CHAT_ID = -1
BOT_TOKEN = 'YOURTOKENHERE'
async def notify(request):
try:
post_data = await request.post()
text = post_data.get('text', '')
with aiohttp.ClientSession() as session:
async with session.post('https://api.telegram.org/bot%s/sendMessage' % BOT_TOKEN, data={"chat_id": CHAT_ID, "text": text}) as resp:
if resp.status != 200:
raise Exception('get fucked')
return web.Response(text='0', status=200)
except Exception as e:
print(e)
return web.Response(text='1', status=400)
if __name__ == "__main__":
app = web.Application()
app.router.add_post('/notify', notify)
web.run_app(app, host='0.0.0.0', port=20080)
@ly0
Copy link
Author

ly0 commented Dec 10, 2017

Caveat

this thread intends to make you feel how convenient the telegram bot is when you wanna send a notification or some short messages, codes are only just a way to express this (they are truly working in production)

Demo: Send a message when user logon via SSH

Edit /etc/profile.d/ssh_login_notify.sh

#!/bin/sh
curl -s http://YOURIP:20080/notify --data "text=Server:$(curl -s http://api.ipify.org)  $USER just login at $(TZ="Asia/Shanghai" date -Is)"

Then make the script executable.
chmod +x /etc/profile.d/ssh_login_notify.sh

Screenshot:
image

@ly0
Copy link
Author

ly0 commented Dec 10, 2017

If you don't care the token security of your telegram bot, you can even use a simpler way to send a message (even without python!).

curl --data-urlencode "chat_id=CHAT_ID" --data-urlencode "text=Server:$(curl -s http://api.ipify.org)  $USER just login at $(TZ="Asia/Shanghai" date -Is)" https://api.telegram.org/bot[BOT_TOKEN]/sendMessage

OR If your server in CHINA, emmmm....
maybe you want some Shadow things?

curl --socks5 127.0.0.1:1080 --data-urlencode "chat_id=CHAT_ID" --data-urlencode "text=Server:$(curl -s http://api.ipify.org)  $USER just login at $(TZ="Asia/Shanghai" date -Is)" https://api.telegram.org/bot[BOT_TOKEN]/sendMessage

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment