FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
python-telegram-bot/examples/contexttypesbot.py at master · python-telegram-bot/python-telegram-bot · GitHub
Uh oh!
There was an error while loading.
Please reload this page
.
python-telegram-bot
/
python-telegram-bot
Public
Notifications
You must be signed in to change notification settings
Fork
6.1k
Star
29.4k
Code
Issues
25
Pull requests
16
Discussions
Actions
Projects
Wiki
Security and quality
0
Insights
Additional navigation options
Code
Issues
Pull requests
Discussions
Actions
Projects
Wiki
Security and quality
Insights
Expand file tree
Breadcrumbs
python-telegram-bot
/
examples
/
contexttypesbot.py
Copy path
More file actions
More file actions
Latest commit
History
History
History
142 lines (110 loc) · 4.73 KB
Breadcrumbs
python-telegram-bot
/
examples
/
contexttypesbot.py
Copy path
File metadata and controls
142 lines (110 loc) · 4.73 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
#!/usr/bin/env python
# pylint: disable=unused-argument
# This program is dedicated to the public domain under the CC0 license.
"""
Simple Bot to showcase `telegram.ext.ContextTypes`.
Usage:
Press Ctrl-C on the command line or send a signal to the process to stop the
bot.
"""
import
logging
from
collections
import
defaultdict
from
telegram
import
InlineKeyboardButton
,
InlineKeyboardMarkup
,
Update
from
telegram
.
constants
import
ParseMode
from
telegram
.
ext
import
(
Application
,
CallbackContext
,
CallbackQueryHandler
,
CommandHandler
,
ContextTypes
,
ExtBot
,
TypeHandler
,
)
# 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__
)
class
ChatData
:
"""Custom class for chat_data. Here we store data per message."""
def
__init__
(
self
)
->
None
:
self
.
clicks_per_message
:
defaultdict
[
int
,
int
]
=
defaultdict
(
int
)
# The [ExtBot, dict, ChatData, dict] is for type checkers like mypy
class
CustomContext
(
CallbackContext
[
ExtBot
,
dict
,
ChatData
,
dict
]):
"""Custom class for context."""
def
__init__
(
self
,
application
:
Application
,
chat_id
:
int
|
None
=
None
,
user_id
:
int
|
None
=
None
,
):
super
().
__init__
(
application
=
application
,
chat_id
=
chat_id
,
user_id
=
user_id
)
self
.
_message_id
:
int
|
None
=
None
@
property
def
bot_user_ids
(
self
)
->
set
[
int
]:
"""Custom shortcut to access a value stored in the bot_data dict"""
return
self
.
bot_data
.
setdefault
(
"user_ids"
,
set
())
@
property
def
message_clicks
(
self
)
->
int
|
None
:
"""Access the number of clicks for the message this context object was built for."""
if
self
.
_message_id
:
return
self
.
chat_data
.
clicks_per_message
[
self
.
_message_id
]
return
None
@
message_clicks
.
setter
def
message_clicks
(
self
,
value
:
int
)
->
None
:
"""Allow to change the count"""
if
not
self
.
_message_id
:
raise
RuntimeError
(
"There is no message associated with this context object."
)
self
.
chat_data
.
clicks_per_message
[
self
.
_message_id
]
=
value
@
classmethod
def
from_update
(
cls
,
update
:
object
,
application
:
"Application"
)
->
"CustomContext"
:
"""Override from_update to set _message_id."""
# Make sure to call super()
context
=
super
().
from_update
(
update
,
application
)
if
context
.
chat_data
and
isinstance
(
update
,
Update
)
and
update
.
effective_message
:
# pylint: disable=protected-access
context
.
_message_id
=
update
.
effective_message
.
message_id
# Remember to return the object
return
context
async
def
start
(
update
:
Update
,
context
:
CustomContext
)
->
None
:
"""Display a message with a button."""
await
update
.
message
.
reply_html
(
"This button was clicked <i>0</i> times."
,
reply_markup
=
InlineKeyboardMarkup
.
from_button
(
InlineKeyboardButton
(
text
=
"Click me!"
,
callback_data
=
"button"
)
),
)
async
def
count_click
(
update
:
Update
,
context
:
CustomContext
)
->
None
:
"""Update the click count for the message."""
context
.
message_clicks
+=
1
await
update
.
callback_query
.
answer
()
await
update
.
effective_message
.
edit_text
(
f"This button was clicked <i>
{
context
.
message_clicks
}
</i> times."
,
reply_markup
=
InlineKeyboardMarkup
.
from_button
(
InlineKeyboardButton
(
text
=
"Click me!"
,
callback_data
=
"button"
)
),
parse_mode
=
ParseMode
.
HTML
,
)
async
def
print_users
(
update
:
Update
,
context
:
CustomContext
)
->
None
:
"""Show which users have been using this bot."""
await
update
.
message
.
reply_text
(
f"The following user IDs have used this bot:
{
', '
.
join
(
map
(
str
,
context
.
bot_user_ids
))
}
"
)
async
def
track_users
(
update
:
Update
,
context
:
CustomContext
)
->
None
:
"""Store the user id of the incoming update, if any."""
if
update
.
effective_user
:
context
.
bot_user_ids
.
add
(
update
.
effective_user
.
id
)
def
main
()
->
None
:
"""Run the bot."""
context_types
=
ContextTypes
(
context
=
CustomContext
,
chat_data
=
ChatData
)
application
=
Application
.
builder
().
token
(
"TOKEN"
).
context_types
(
context_types
).
build
()
# run track_users in its own group to not interfere with the user handlers
application
.
add_handler
(
TypeHandler
(
Update
,
track_users
),
group
=
-
1
)
application
.
add_handler
(
CommandHandler
(
"start"
,
start
))
application
.
add_handler
(
CallbackQueryHandler
(
count_click
))
application
.
add_handler
(
CommandHandler
(
"print_users"
,
print_users
))
application
.
run_polling
(
allowed_updates
=
Update
.
ALL_TYPES
)
if
__name__
==
"__main__"
:
main
()
Back
|
FazBrowse Home
|
New Git URL