-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathinline_query_example.py
79 lines (64 loc) · 2.24 KB
/
inline_query_example.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
75
76
77
78
79
import logging
import json
from typing import Tuple
from swibots import (
BotApp,
BotContext,
MessageEvent,
Message,
InlineQuery,
InlineQueryEvent,
RestClient,
RestResponse,
JSONDict,
NetworkError,
InlineQueryResultArticle,
InputMessageContent,
)
logging.basicConfig(level=logging.DEBUG)
log = logging.getLogger(__name__)
restclient = RestClient()
def parse_response(response: Tuple[int, bytes]) -> RestResponse[JSONDict]:
decoded_s = response[1].decode("utf-8", "replace")
try:
jsonObject = json.loads(decoded_s)
except ValueError as exc:
jsonObject = decoded_s
response = RestResponse(jsonObject, response[0], {})
if response.is_error:
raise NetworkError(response.error_message)
return response
TOKEN = "TOKEN"
app = BotApp(TOKEN, "This is an inline query bot")
@app.on_message()
async def on_message(ctx: BotContext[MessageEvent]):
message: Message = ctx.event.message
log.info(f"Message: {message.message}")
await message.reply_text(f"Echo: {message.message}")
@app.on_inline_query()
async def on_inline_query(ctx: BotContext[InlineQueryEvent]):
query: InlineQuery = ctx.event.query
log.info(f"Inline query: {query.query}")
await query.answer(f"Searching results for {query.query}...")
url = f"https://en.wikipedia.org/w/api.php?action=opensearch&format=json&search={query.query}&limit=50"
response = parse_response(await restclient.get(url))
if response.status_code == 200:
data = response.data
results = []
for i in range(len(data[1])):
results.append(
InlineQueryResultArticle(
id=str(i),
title=data[1][i],
description=data[1][i],
input_message=InputMessageContent(data[2][i]),
article_url=data[3][i],
thumb_url="https://upload.wikimedia.org/wikipedia/commons/thumb/8/80/Wikipedia-logo-v2.svg/1200px-Wikipedia-logo-v2.svg.png",
thumb_width=48,
thumb_height=48,
)
)
await query.answer(results)
else:
await query.answer("There was an error while searching for results.")
app.run()