#!/bin/env python3 # scel-buc - scripts to send and receive messages through a Telegram bot # Copyright (C) 2023 bursa-pastoris # # This file is part of scel-buc. # # scel-buc is free software: you can redistribute it and/or modify it under the # terms of the GNU Affero General Public License as published by the Free # Software Foundation, version 3 of the License. # # scel-buc is distributed in the hope that it will be useful, but WITHOUT ANY # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR # A PARTICULAR PURPOSE. See the GNU Affero General Public License for more # details. # # You should have received a copy of the GNU Affero General Public License # along with scel-buc. If not, see . import urllib.request, urllib.parse import json from datetime import datetime as dt from constants import * def write_msg(msg): # If a name is registered for the sender it is used, otherwise a "name" is # simulated with sender's Telegram ID sender_name = USER # Group log files are named after the group, single chat log files are # named after the sender (be it registered or not) chat_id = str(msg['chat']['id']) if 'title' in msg['chat']: # Chat is group chat. # If a name is registered for the chat it is used, otherwise the group # chat title from Telegram is used. if chat_id in GROUP_NAMES: file_id = f'GRP-{chat_id}-'+GROUP_NAMES[chat_id] else: file_id = f'GRP-{chat_id}-'+str(msg['chat']['title']) elif chat_id in USER_NAMES: # Chat is single chat with a registered user file_id = f'SIN-{chat_id}-'+USER_NAMES[chat_id] else: # Chat is single chat with unregistered user file_id = f'SIN-{chat_id}' # Get message txt... if 'text' in msg: text = msg['text'] else: text = '[unsupported message type]' # ...and date. time = dt.strftime(dt.utcfromtimestamp(msg['date']), '%Y-%m-%d %H:%M:%S') # Write the message message = f'[{time}] {sender_name}\n{text}\n' with open(CHAT_PATH+file_id, 'a') as f: f.write('\n') f.write(message) # Connect to Telegram API with urllib.request.urlopen(f'https://api.telegram.org/bot{TOKEN}/getMe') as request: data = json.loads(request.read()) bot = data['result'] bot_name = '@'+bot['username'] print(f'Sending message for {USER} from {bot_name}...') # Send message recipient = input('Recipient ID > ') text = [] print('Message content. Hit Enter to confirm the line and Ctrl+D to confirm' ' the message.') while True: try: l = input('> ') except EOFError: print() break text.append(l) text = urllib.parse.quote('\n'.join(text)) with urllib.request.urlopen(f'https://api.telegram.org/bot{TOKEN}/sendMessage?chat_id={recipient}&text={text}') as request: data = json.loads(request.read()) if not data['ok']: print("Error {data['error_code']: {data['decription']}") else: print('Sent') write_msg(data['result'])