728x90
반응형
SMALL
오늘은 예상 금액 범위에 도달 했을때 알림 메세지 보내기를 하도록 하겠습니다.
메신저는 텔레그램을 사용하도록 하겠습니다.
이유는 공짜라서요~^^
1. 텔레그램 봇 만들기
- 텔레그램을 열고 @BotFather(봇 생성 및 관리를 위한 공식 텔레그램 봇)를 검색하세요.
- @BotFather와 채팅을 시작하고 /newbot 명령을 사용하여 새 봇을 만듭니다.
- 봇의 이름과 사용자 이름을 선택하세요.
- 일단 생성되면 BotFather는 토큰을 제공합니다. 이 토큰은 Python 스크립트에서 인증에 사용됩니다.
2. 채팅 ID 받기
- 봇을 생성한 후 메시지를 보냅니다. 다음 URL을 방문하여 채팅 ID를 검색할 수 있습니다.
요청 | https://api.telegram.org/bot<your_bot_token>/getUpdates |
결과 | { "ok": true, "result": [ { "update_id": 123456789, "message": { "message_id": 1, "from": { "id": 123456789, "is_bot": false, "first_name": "John", "username": "johndoe", "language_code": "en" }, "chat": { "id": 123456789, "first_name": "John", "username": "johndoe", "type": "private" }, "date": 1632579073, "text": "Hello" } } ]} |
3. 메세지 및 이미지 발송 Python 프로그램
import requests
import os
# Replace with your bot's token
BOT_TOKEN = '7675479808:AAGeA5e8dUGdW17fKTDLIf6LBJlXskXjeqs'# Replace with your chat ID (can be obtained by sending a message to your bot and inspecting the response)
CHAT_ID = '2125429208'# Message to send
# MESSAGE = 'Hello! This is a test message from Python.'
# IMAGE_PATH = 'D:\work\python\Finance\stations.png'
# Function to send message
def send_telegram_message(chat_id, message, image_path=None):
# Send message first
payload = {
'chat_id': chat_id,
'text': message,
'parse_mode': 'HTML' # 'Markdown' or use 'HTML' for HTML formatting
}
response = requests.post(url, data=payload)
if response.status_code == 200:
print("Message sent successfully!")
else:
print(f"Failed to send message: {response.status_code}, {response.text}")
# Check if the image file exists and send the image
if image_path and os.path.exists(image_path):
send_telegram_image(chat_id, image_path)
# else:
# print("No image found or invalid path. Message sent without an image.")
# Function to send an image
def send_telegram_image(chat_id, image_path):
files = {'photo': open(image_path, 'rb')}
data = {'chat_id': chat_id}
response = requests.post(url, files=files, data=data)
if response.status_code == 200:
print("Image sent successfully!")
else:
print(f"Failed to send image: {response.status_code}, {response.text}")
# Example usage
# send_telegram_message(CHAT_ID, '매도!', 'D:\work\python\Finance\samsung_stock.png') #메세지, 이미지 발송
# send_telegram_message(CHAT_ID, '삼성전자 59,700 매수!') #메세지 발송
# send_telegram_message(CHAT_ID, '*Hello!* This is a message with _italic_, **bold**, and `monospace` text.') #'parse_mode': 'Markdown' 메세지에 굵게, 기울임꼴, 고정폭 적용
# send_telegram_message(CHAT_ID, 'Click here 삼성전자 59,700 매수!') #'parse_mode': 'HTML' 링크 삽입
telegram_messgae_sender.py
0.00MB
samsung_stock.png
0.04MB
728x90
반응형
LIST
'python' 카테고리의 다른 글
[데이터 수집] 주식 데이터 수집(특정 시간 단위로) (6) | 2024.10.10 |
---|---|
특정 폴더 내 파일 파싱(parsing)하여 IP 검출 (0) | 2024.08.06 |
[Python] 오프라인 환경에서 패키지 설치 (0) | 2024.06.29 |
[Python] MariaDB 접속 후 테이블 조회 (0) | 2024.06.29 |