or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

bot-core.mdchat-management.mdhandler-system.mdindex.mdinteractive-elements.mdmedia-handling.mdmessage-operations.mdupdate-processing.md

handler-system.mddocs/

0

# Handler System

1

2

Comprehensive event handling system supporting message handlers, callback query handlers, inline handlers, and various other update types with filtering capabilities.

3

4

## Capabilities

5

6

### Message Handlers

7

8

Register handlers for different types of messages with filtering by commands, content types, and custom functions.

9

10

```python { .api }

11

def message_handler(self, commands: Optional[List[str]] = None,

12

regexp: Optional[str] = None,

13

func: Optional[Callable] = None,

14

content_types: Optional[List[str]] = None, **kwargs):

15

"""

16

Decorator for message handling with various filters.

17

18

Parameters:

19

- commands (List[str], optional): Bot commands to handle (['start', 'help'])

20

- regexp (str, optional): Regular expression pattern for text matching

21

- func (Callable, optional): Custom filter function receiving message

22

- content_types (List[str], optional): Content types to handle (default: ['text'])

23

- **kwargs: Additional filter parameters

24

25

Usage:

26

@bot.message_handler(commands=['start'])

27

@bot.message_handler(content_types=['photo', 'video'])

28

@bot.message_handler(func=lambda msg: msg.text and 'hello' in msg.text.lower())

29

"""

30

31

def add_message_handler(self, handler_dict):

32

"""

33

Programmatically add message handler.

34

35

Parameters:

36

- handler_dict (dict): Handler configuration dictionary

37

"""

38

39

def register_message_handler(self, callback: Callable, content_types: Optional[List[str]] = None,

40

commands: Optional[List[str]] = None, regexp: Optional[str] = None,

41

func: Optional[Callable] = None, **kwargs):

42

"""

43

Register message handler without decorator.

44

45

Parameters:

46

- callback (Callable): Handler function

47

- content_types (List[str], optional): Content types to handle

48

- commands (List[str], optional): Commands to handle

49

- regexp (str, optional): Regular expression pattern

50

- func (Callable, optional): Custom filter function

51

"""

52

```

53

54

### Callback Query Handlers

55

56

Handle button clicks from inline keyboards.

57

58

```python { .api }

59

def callback_query_handler(self, func: Callable, **kwargs):

60

"""

61

Decorator for callback query handling.

62

63

Parameters:

64

- func (Callable): Filter function for callback queries

65

- **kwargs: Additional filter parameters

66

67

Usage:

68

@bot.callback_query_handler(func=lambda call: call.data.startswith('btn_'))

69

"""

70

71

def answer_callback_query(self, callback_query_id: int, text: Optional[str] = None,

72

show_alert: Optional[bool] = None, url: Optional[str] = None,

73

cache_time: Optional[int] = None) -> bool:

74

"""

75

Answer callback queries from inline keyboards.

76

77

Parameters:

78

- callback_query_id (int): Unique identifier for the query

79

- text (str, optional): Text notification to show (0-200 characters)

80

- show_alert (bool, optional): Show alert instead of notification

81

- url (str, optional): URL to open by the client

82

- cache_time (int, optional): Cache time for the answer

83

84

Returns:

85

bool: True on success

86

"""

87

```

88

89

### Next Step and Reply Handlers

90

91

Handle conversational flow and replies to specific messages.

92

93

```python { .api }

94

def register_next_step_handler(self, message: types.Message, callback: Callable,

95

*args, **kwargs) -> None:

96

"""

97

Register handler for next message from user in same chat.

98

99

Parameters:

100

- message (Message): Message that triggers next step handling

101

- callback (Callable): Function to call on next message

102

- *args: Arguments to pass to callback

103

- **kwargs: Keyword arguments to pass to callback

104

"""

105

106

def register_next_step_handler_by_chat_id(self, chat_id: Union[int, str], callback: Callable,

107

*args, **kwargs) -> None:

108

"""

109

Register next step handler by chat ID.

110

111

Parameters:

112

- chat_id (Union[int, str]): Chat ID to monitor

113

- callback (Callable): Handler function

114

- *args: Arguments to pass to callback

115

- **kwargs: Keyword arguments to pass to callback

116

"""

117

118

def register_for_reply(self, message: types.Message, callback: Callable,

119

*args, **kwargs) -> None:

120

"""

121

Register handler for replies to specific message.

122

123

Parameters:

124

- message (Message): Message to wait for replies to

125

- callback (Callable): Function to call when reply received

126

- *args: Arguments to pass to callback

127

- **kwargs: Keyword arguments to pass to callback

128

"""

129

130

def clear_step_handler(self, message: types.Message) -> None:

131

"""Clear next step handlers for a chat."""

132

133

def clear_reply_handlers(self, message: types.Message) -> None:

134

"""Clear reply handlers for a message."""

135

```

136

137

### Specialized Handlers

138

139

Handle various other update types including inline queries, polls, and chat member changes.

140

141

```python { .api }

142

def inline_handler(self, func: Callable, **kwargs):

143

"""

144

Decorator for inline query handling.

145

146

Parameters:

147

- func (Callable): Filter function for inline queries

148

"""

149

150

def poll_handler(self, func: Callable, **kwargs):

151

"""

152

Decorator for poll update handling.

153

154

Parameters:

155

- func (Callable): Filter function for polls

156

"""

157

158

def poll_answer_handler(self, func: Optional[Callable] = None, **kwargs):

159

"""

160

Decorator for poll answer handling.

161

162

Parameters:

163

- func (Callable, optional): Filter function for poll answers

164

"""

165

166

def my_chat_member_handler(self, func: Optional[Callable] = None, **kwargs):

167

"""

168

Decorator for bot's chat membership changes.

169

170

Parameters:

171

- func (Callable, optional): Filter function for membership changes

172

"""

173

174

def chat_member_handler(self, func: Optional[Callable] = None, **kwargs):

175

"""

176

Decorator for chat member status changes.

177

178

Parameters:

179

- func (Callable, optional): Filter function for member changes

180

"""

181

```

182

183

### Middleware System

184

185

Add middleware for preprocessing updates before handlers.

186

187

```python { .api }

188

def middleware_handler(self, update_types: Optional[List[str]] = None):

189

"""

190

Decorator for middleware handlers.

191

192

Parameters:

193

- update_types (List[str], optional): Update types to process

194

(['message', 'callback_query', 'inline_query', etc.])

195

196

Usage:

197

@bot.middleware_handler(['message'])

198

def log_messages(bot_instance, message):

199

print(f"Received: {message.text}")

200

"""

201

202

def add_middleware_handler(self, handler: Callable, update_types: Optional[List[str]] = None):

203

"""

204

Add middleware handler programmatically.

205

206

Parameters:

207

- handler (Callable): Middleware function

208

- update_types (List[str], optional): Update types to process

209

"""

210

```

211

212

## Usage Examples

213

214

### Basic Message Handler

215

216

```python

217

@bot.message_handler(commands=['start', 'help'])

218

def send_welcome(message):

219

bot.reply_to(message, "Hello! How can I help you?")

220

221

@bot.message_handler(content_types=['photo'])

222

def handle_photo(message):

223

bot.reply_to(message, "Nice photo!")

224

225

@bot.message_handler(func=lambda msg: msg.text and 'hello' in msg.text.lower())

226

def handle_hello(message):

227

bot.reply_to(message, "Hello there!")

228

```

229

230

### Conversational Flow Example

231

232

```python

233

@bot.message_handler(commands=['name'])

234

def ask_name(message):

235

msg = bot.reply_to(message, "What's your name?")

236

bot.register_next_step_handler(msg, process_name)

237

238

def process_name(message):

239

name = message.text

240

msg = bot.reply_to(message, f"Nice to meet you, {name}! How old are you?")

241

bot.register_next_step_handler(msg, process_age, name)

242

243

def process_age(message, name):

244

try:

245

age = int(message.text)

246

bot.reply_to(message, f"Great! {name}, you are {age} years old.")

247

except ValueError:

248

msg = bot.reply_to(message, "Please enter a valid number:")

249

bot.register_next_step_handler(msg, process_age, name)

250

```

251

252

### Inline Keyboard and Callback Example

253

254

```python

255

from telebot import types

256

257

@bot.message_handler(commands=['menu'])

258

def show_menu(message):

259

markup = types.InlineKeyboardMarkup()

260

markup.row(

261

types.InlineKeyboardButton("Option 1", callback_data="opt1"),

262

types.InlineKeyboardButton("Option 2", callback_data="opt2")

263

)

264

bot.send_message(message.chat.id, "Choose an option:", reply_markup=markup)

265

266

@bot.callback_query_handler(func=lambda call: call.data.startswith('opt'))

267

def handle_menu_callback(call):

268

bot.answer_callback_query(call.id)

269

270

if call.data == "opt1":

271

bot.send_message(call.message.chat.id, "You chose Option 1!")

272

elif call.data == "opt2":

273

bot.send_message(call.message.chat.id, "You chose Option 2!")

274

```

275

276

### Middleware Example

277

278

```python

279

# Enable middleware

280

import telebot.apihelper

281

telebot.apihelper.ENABLE_MIDDLEWARE = True

282

283

@bot.middleware_handler(['message'])

284

def log_messages(bot_instance, message):

285

print(f"User {message.from_user.id} sent: {message.text}")

286

287

@bot.middleware_handler() # All update types

288

def security_check(bot_instance, update):

289

# Add security checks, rate limiting, etc.

290

pass

291

```

292

293

## Types

294

295

```python { .api }

296

class CallbackQuery:

297

id: str

298

from_user: User

299

message: Optional[Message]

300

inline_message_id: Optional[str]

301

chat_instance: str

302

data: Optional[str]

303

game_short_name: Optional[str]

304

305

class InlineQuery:

306

id: str

307

from_user: User

308

query: str

309

offset: str

310

chat_type: Optional[str]

311

location: Optional[Location]

312

313

class Poll:

314

id: str

315

question: str

316

options: List[PollOption]

317

total_voter_count: int

318

is_closed: bool

319

is_anonymous: bool

320

type: str

321

allows_multiple_answers: bool

322

323

class PollAnswer:

324

poll_id: str

325

user: User

326

option_ids: List[int]

327

328

class ChatMemberUpdated:

329

chat: Chat

330

from_user: User

331

date: int

332

old_chat_member: ChatMember

333

new_chat_member: ChatMember

334

invite_link: Optional[ChatInviteLink]

335

```