-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.py
executable file
·74 lines (67 loc) · 2.27 KB
/
server.py
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
import asyncio
import uvicorn
from fastapi import FastAPI
from telethon import TelegramClient, events, utils, sync
import time
from dotenv import load_dotenv
import os
# For async, not worked with uvicorn or need to know how
# api_id = int(os.environ.get("api_id"))
# api_hash = os.environ.get("api_hash")
# client = TelegramClient('test', api_id, api_hash)
app = FastAPI()
@app.get("/history")
def make_response():
load_dotenv()
api_id = int(os.environ.get("api_id"))
api_hash = os.environ.get("api_hash")
chat = os.environ.get("chat")
asyncio.set_event_loop(asyncio.new_event_loop())
client = TelegramClient('test', api_id, api_hash)
client.start()
# init all chats to session - without it first time don't work client.send_message(chat, 'history')
dialogs = client.iter_dialogs()
# Send message "history"
client.send_message(chat, 'history')
id_mes = 0
# Take id last message "history"
for message in client.iter_messages(chat):
if message.text == 'history':
id_mes = message.id
print(id_mes)
break
# wait to take answer hummingbot to telegramm chat
time.sleep(15)
# take messages after message history
history = []
for message in client.iter_messages(chat, reverse=True):
if message.id > id_mes:
history.append(message.text)
# history = "".join(history)
client.disconnect()
return history
# async version
# async def history():
# chat = os.environ.get("chat")
# await client.send_message(chat, 'history')
# id_mes = 0
# async for message in client.iter_messages(chat):
# if message.text == 'history':
# id_mes = message.id
# print(id_mes)
# break
# await asyncio.sleep(15)
# # async for message in client.iter_messages('HammingDev', from_user='HammingDev'):
# history = []
# async for message in client.iter_messages(chat, reverse=True):
# if message.id > id_mes:
# print(message.id, message.text)
# # history += message.text
# history.extend(message.text)
# # history = "".join(history)
# return history
if __name__ == "__main__":
uvicorn.run("server:app",
host="0.0.0.0",
port=9400,
)