-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathlower_button
57 lines (47 loc) · 2.02 KB
/
lower_button
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import logging
from flask import Flask, request, jsonify
import requests
import os
app = Flask(__name__)
# Set up logging
logging.basicConfig(level=logging.DEBUG)
TELEGRAM_BOT_TOKEN = os.getenv('6571192837:AAFG994S5fuEmrbfxDluOPKMCgj0kKzJZCA')
TELEGRAM_CHAT_ID = os.getenv('6571192837')
def send_telegram_message(message, chat_id):
"""Send a message to a Telegram chat using the bot API."""
url = f'https://api.telegram.org/bot{TELEGRAM_BOT_TOKEN}/sendMessage'
payload = {
'chat_id': chat_id,
'text': message
}
try:
response = requests.post(url, data=payload)
response.raise_for_status()
logging.info(f'Sent message to {chat_id}: {message}')
return response
except requests.exceptions.HTTPError as errh:
logging.error(f'HTTP Error: {errh}')
except requests.exceptions.ConnectionError as errc:
logging.error(f'Error Connecting: {errc}')
except requests.exceptions.Timeout as errt:
logging.error(f'Timeout Error: {errt}')
except requests.exceptions.RequestException as err:
logging.error(f'Something went wrong: {err}')
@app.route('/send_alert', methods=['POST'])
def send_alert():
"""API endpoint to send an alert message via Telegram."""
data = request.json
region = data.get('region')
chat_id = data.get('chat_id', TELEGRAM_CHAT_ID)
if not region or not chat_id:
logging.warning('Region and chat_id are required but not provided')
return jsonify({'error': 'Region and chat_id are required'}), 400
message = f'Alert: Possible landslide detected in {region}.'
response = send_telegram_message(message, chat_id)
if response and response.status_code == 200:
return jsonify({'status': 'success', 'message': 'Alert sent successfully!'}), 200
else:
logging.error(f'Failed to send message: {response.text}')
return jsonify({'error': 'Failed to send message', 'details': response.json()}), 500
if __name__ == '__main__':
app.run(debug=True, host='0.0.0.0', port=5000)