-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathtelegram_demo.py
More file actions
231 lines (163 loc) · 7.44 KB
/
telegram_demo.py
File metadata and controls
231 lines (163 loc) · 7.44 KB
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
"""
Simple bot to respond to different kinds of messages.
```python
python demo.py
```
Press Ctrl-C on the command line to stop the bot.
"""
from data_utils.preprocessing import fcgr
import logging
from telegram import ForceReply, Update
from telegram.ext import Application, CommandHandler, ContextTypes, MessageHandler, filters
from keys import TELEGRAM_KEY
import numpy as np
from io import BytesIO
from telegram import Update
from telegram.ext import ContextTypes # Make sure you import the correct ContextTypes
from PIL import Image
import numpy as np
# Enable logging
logging.basicConfig(
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO
)
# set higher logging level for httpx to avoid all GET and POST requests being logged
logging.getLogger("httpx").setLevel(logging.WARNING)
logger = logging.getLogger(__name__)
# Define a few command handlers. These usually take the two arguments update and
# context.
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
"""Send a message when the command /start is issued."""
user = update.effective_user
await update.message.reply_html(
rf"Hi {user.mention_html()}!",
reply_markup=ForceReply(selective=True),
)
async def help_command(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
"""Send a message when the command /help is issued."""
await update.message.reply_text("Help!")
async def echo(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
"""Echo the user message."""
await update.message.reply_text(update.message.text)
async def message(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
if set(update.message.text.upper()) <= set("ATCG"):
k = np.min([6, len(update.message.text)//3])
fcgr_image = fcgr(update.message.text.upper(), k=k)
# Convert NumPy array to unsigned 8-bit integer array
fcgr_image_uint8 = (fcgr_image * 255 / np.max(fcgr_image)).astype(np.uint8)
# Convert NumPy array to PIL Image
pil_image = Image.fromarray(fcgr_image_uint8)
# Save the PIL Image to a BytesIO object
image_buffer = BytesIO()
pil_image.save(image_buffer, format="PNG")
image_buffer.seek(0)
# Reply with the photo
await update.message.reply_photo(photo=image_buffer, caption=f"Image shape: {fcgr_image.shape}. DNA sequence length: {len(update.message.text)}")
else:
await update.message.reply_text("Not a DNA sequence")
async def photo(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
"""Echo user photo."""
photo_file = await update.message.photo[-1].get_file()
# load image into numpy array
tmp_photo = "tmp_photo.jpg"
await photo_file.download_to_drive(tmp_photo)
img = np.array(Image.open(tmp_photo))
# respond photo
await update.message.reply_photo(tmp_photo, caption=f"Image shape: {img.shape}")
# async def voice(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
# """Echo user audio."""
# audio_file = await update.message.voice.get_file()
# # load audio into numpy array
# tmp_file = "voice_note.ogg"
# await audio_file.download_to_drive(tmp_file)
# signal, sampling_rate = audiofile.read(tmp_file, always_2d=True)
# duration = signal.shape[1] / sampling_rate
# # respond audio
# await update.message.reply_voice(tmp_file, caption=f"Voice note duration: {duration} seconds")
# async def audio(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
# """Echo user audio."""
# audio_file = await update.message.audio.get_file()
# # load audio into numpy array
# tmp_file = "audio.wav"
# await audio_file.download_to_drive(tmp_file)
# signal, sampling_rate = audiofile.read(tmp_file, always_2d=True)
# duration = signal.shape[1] / sampling_rate
# # respond audio
# await update.message.reply_audio(tmp_file, caption=f"Audio duration: {duration} seconds")
async def attachment(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
"""Echo user attachment."""
attachment_file = await update.message.document.get_file()
# download pdf and send back
tmp_file = "attachment.pdf"
await attachment_file.download_to_drive(tmp_file)
# read PDF
reader = PdfReader(tmp_file)
# get title and number of pagers
title = reader.Info.Title
num_pages = len(reader.pages)
# respond attachment
await update.message.reply_document(tmp_file, caption=f"PDF title: {title}, number of pages: {num_pages}")
async def alarm(context: ContextTypes.DEFAULT_TYPE) -> None:
"""Send the alarm message."""
job = context.job
await context.bot.send_message(job.chat_id, text=f"Beep! {job.data} seconds are over!")
def remove_job_if_exists(name: str, context: ContextTypes.DEFAULT_TYPE) -> bool:
"""Remove job with given name. Returns whether job was removed."""
current_jobs = context.job_queue.get_jobs_by_name(name)
if not current_jobs:
return False
for job in current_jobs:
job.schedule_removal()
return True
async def set_timer(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
"""Add a job to the queue."""
chat_id = update.effective_message.chat_id
try:
# args[0] should contain the time for the timer in seconds
due = float(context.args[0])
if due < 0:
await update.effective_message.reply_text("Sorry we can not go back to future!")
return
job_removed = remove_job_if_exists(str(chat_id), context)
context.job_queue.run_once(alarm, due, chat_id=chat_id, name=str(chat_id), data=due)
text = "Timer successfully set!"
if job_removed:
text += " Old one was removed."
await update.effective_message.reply_text(text)
except (IndexError, ValueError):
await update.effective_message.reply_text("Usage: /timer <seconds>")
async def how_are_you(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
"""Select from randomly from set responses."""
responses = ["Fine", "Good", "Bad", "So so"]
await update.message.reply_text(np.random.choice(responses))
def main() -> None:
"""Start the bot."""
# Create the Application and pass it your bot's token.
application = Application.builder().token(TELEGRAM_KEY).build()
# on different commands - answer in Telegram
application.add_handler(CommandHandler("start", start))
application.add_handler(CommandHandler("help", help_command))
# menu commands
application.add_handler(CommandHandler("timer", set_timer))
application.add_handler(CommandHandler("howareyou", how_are_you))
# on non command i.e message - echo the message on Telegram
application.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, message))
# photo input
application.add_handler(
MessageHandler(filters.PHOTO & ~filters.COMMAND, photo, block=True)
)
# # voice input
# application.add_handler(
# MessageHandler(filters.VOICE & ~filters.COMMAND, voice, block=True)
# )
# # audio input
# application.add_handler(
# MessageHandler(filters.AUDIO & ~filters.COMMAND, audio, block=True)
# )
# attachments
application.add_handler(
MessageHandler(filters.ATTACHMENT & ~filters.COMMAND, attachment, block=True)
)
# Run the bot until the user presses Ctrl-C
application.run_polling(allowed_updates=Update.ALL_TYPES)
if __name__ == "__main__":
main()