pip install python-telegram-bot --upgrade
import requests, json
def get_all_rooms(token, personal=True):
rooms = {}
url = f'https://api.telegram.org/bot{token}/getUpdates'
print(url)
r = requests.get(url)
d = json.loads(r.text)
if not d['ok']:
return None
if 'result' in d.keys():
for e in d['result']:
key = ''
if 'my_chat_member' in e.keys():
key = 'my_chat_member'
elif 'message' in e.keys():
key = 'message'
elif 'channel_post' in e.keys():
key = 'channel_post'
if key and 'title' in e[key]['chat'].keys(): # title이 없으면 개인톡임
room_id = str(e[key]['chat']['id'])
room_title = e[key]['chat']['title']
rooms[room_id] = room_title
if personal:
chatid = e[key]['chat']["id"]
username = e[key]['chat']["username"]
rooms[chatid] = username
return rooms
token = "<BOT TOKEN>" # 봇 토큰 지정
rooms = get_all_rooms(token)
print(json.dumps(rooms, indent=2, ensure_ascii=False))
import telegram
chat_id = "<CHAT ID>" # 채팅 아이디 지정
bot = telegram.Bot(token)
# 텍스트 메세지 전송
bot.sendMessage(chat_id=chat_id, text="텍스트 메세지")
# 이미지 전송
with open("sample.png", "rb") as f:
bot.sendPhoto(chat_id=chat_id, photo=f, caption="이미지 캡션")
# 문서 전송
with open("main.py", "rb") as f:
bot.sendDocument(chat_id=chat_id, document=f, filename="test.py")
import telegram
import asyncio
TOKEN = ""
CHAT_ID = ""
async def main():
bot = telegram.Bot(TOKEN)
await bot.send_message(CHAT_ID, "test")
return True
if __name__ == '__main__':
asyncio.get_event_loop().run_until_complete(main())