or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

tessl/pypi-python-telegram-bot

A pure Python, asynchronous interface for the Telegram Bot API with comprehensive wrapper and high-level framework for building sophisticated Telegram bots

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/python-telegram-bot@21.11.x

To install, run

npx @tessl/cli install tessl/pypi-python-telegram-bot@21.11.0

0

# Python Telegram Bot

1

2

A comprehensive, asynchronous Python library providing a complete interface to the Telegram Bot API. This library offers both a pure API wrapper and a high-level framework for building sophisticated Telegram bots with minimal complexity.

3

4

## Package Information

5

6

- **Package Name**: python-telegram-bot

7

- **Language**: Python

8

- **Installation**: `pip install python-telegram-bot`

9

- **Python Version**: 3.9+

10

- **API Version**: Telegram Bot API 8.3

11

12

## Core Imports

13

14

```python

15

from telegram import Bot, Update

16

from telegram.ext import Application, ApplicationBuilder

17

```

18

19

For basic bot functionality:

20

21

```python

22

from telegram import Bot

23

from telegram.ext import Application, CommandHandler, MessageHandler, filters

24

```

25

26

## Basic Usage

27

28

```python

29

import asyncio

30

from telegram import Update

31

from telegram.ext import Application, CommandHandler, ContextTypes

32

33

async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:

34

"""Send a message when the command /start is issued."""

35

await update.message.reply_text('Hi! I am your bot.')

36

37

async def echo(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:

38

"""Echo the user message."""

39

await update.message.reply_text(update.message.text)

40

41

def main() -> None:

42

"""Start the bot."""

43

# Create the Application and pass it your bot's token

44

application = Application.builder().token("YOUR_BOT_TOKEN").build()

45

46

# Register handlers

47

application.add_handler(CommandHandler("start", start))

48

application.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, echo))

49

50

# Run the bot until you press Ctrl-C

51

application.run_polling()

52

53

if __name__ == '__main__':

54

main()

55

```

56

57

## Architecture

58

59

The library is structured around two main layers:

60

61

- **Core API Layer** (`telegram.*`): Direct wrapper around Telegram Bot API providing all types and methods

62

- **Extension Framework** (`telegram.ext.*`): High-level framework with application management, handlers, persistence, and utilities

63

64

Key components:

65

- **Application**: Central coordinator managing bot lifecycle, handlers, and updates

66

- **Handlers**: Process specific types of updates (commands, messages, callbacks, etc.)

67

- **Bot**: Provides all Telegram Bot API methods for sending messages and managing bot

68

- **Update**: Represents incoming data from Telegram

69

- **Filters**: Filter incoming updates based on criteria

70

71

## Capabilities

72

73

### Bot Core API

74

75

Core Bot class providing all Telegram Bot API methods for sending messages, managing files, handling chats and users, and bot administration.

76

77

```python { .api }

78

class Bot:

79

def __init__(self, token: str, **kwargs): ...

80

async def send_message(self, chat_id: int | str, text: str, **kwargs) -> Message: ...

81

async def send_photo(self, chat_id: int | str, photo: InputFile | str, **kwargs) -> Message: ...

82

async def get_updates(self, **kwargs) -> list[Update]: ...

83

async def get_me() -> User: ...

84

```

85

86

[Bot API](./bot-api.md)

87

88

### Application Framework

89

90

High-level framework for building and managing Telegram bots with handlers, job queues, persistence, and lifecycle management.

91

92

```python { .api }

93

class Application:

94

def add_handler(self, handler: BaseHandler) -> None: ...

95

def run_polling(self, **kwargs) -> None: ...

96

def run_webhook(self, **kwargs) -> None: ...

97

98

class ApplicationBuilder:

99

def token(self, token: str) -> 'ApplicationBuilder': ...

100

def build() -> Application: ...

101

```

102

103

[Application Framework](./application-framework.md)

104

105

### Message Handlers

106

107

Comprehensive handler system for processing different types of updates including commands, messages, callbacks, inline queries, and other Telegram events.

108

109

```python { .api }

110

class CommandHandler(BaseHandler):

111

def __init__(self, command: str, callback: callable, **kwargs): ...

112

113

class MessageHandler(BaseHandler):

114

def __init__(self, filters: BaseFilter, callback: callable, **kwargs): ...

115

116

class CallbackQueryHandler(BaseHandler):

117

def __init__(self, callback: callable, **kwargs): ...

118

```

119

120

[Handlers](./handlers.md)

121

122

### Telegram Types

123

124

Complete type system covering all Telegram Bot API objects including messages, users, chats, files, keyboards, payments, games, and passport data.

125

126

```python { .api }

127

class Update:

128

message: Message | None

129

callback_query: CallbackQuery | None

130

inline_query: InlineQuery | None

131

132

class Message:

133

message_id: int

134

from_user: User | None

135

chat: Chat

136

text: str | None

137

138

class User:

139

id: int

140

is_bot: bool

141

first_name: str

142

username: str | None

143

```

144

145

[Telegram Types](./telegram-types.md)

146

147

### Keyboards and Markup

148

149

Inline and reply keyboards with comprehensive button types including web apps, contact/location requests, and callback data.

150

151

```python { .api }

152

class ReplyKeyboardMarkup:

153

def __init__(self, keyboard: list[list[KeyboardButton]], **kwargs): ...

154

155

class InlineKeyboardMarkup:

156

def __init__(self, inline_keyboard: list[list[InlineKeyboardButton]]): ...

157

158

class KeyboardButton:

159

def __init__(self, text: str, **kwargs): ...

160

161

class InlineKeyboardButton:

162

def __init__(self, text: str, **kwargs): ...

163

```

164

165

[Keyboards](./keyboards.md)

166

167

### File Operations

168

169

Complete file handling including uploads, downloads, and media processing with support for all Telegram file types.

170

171

```python { .api }

172

class InputFile:

173

def __init__(self, obj: BinaryIO | bytes | str): ...

174

175

class File:

176

file_id: str

177

file_unique_id: str

178

file_path: str | None

179

async def download_to_drive(self, custom_path: str = None) -> str: ...

180

```

181

182

[Files](./files.md)

183

184

### Filters System

185

186

Powerful filtering system for precisely targeting which updates handlers should process, with built-in filters and custom filter creation.

187

188

```python { .api }

189

class filters:

190

TEXT: MessageFilter

191

COMMAND: MessageFilter

192

PHOTO: MessageFilter

193

VIDEO: MessageFilter

194

ALL: UpdateFilter

195

```

196

197

[Filters](./filters.md)

198

199

### Advanced Features

200

201

Additional capabilities including job queues, persistence, rate limiting, conversation handling, and webhook management.

202

203

```python { .api }

204

class JobQueue:

205

def run_once(self, callback: callable, when: float, **kwargs) -> Job: ...

206

def run_repeating(self, callback: callable, interval: float, **kwargs) -> Job: ...

207

208

class PicklePersistence(BasePersistence):

209

def __init__(self, filepath: str, **kwargs): ...

210

```

211

212

[Advanced Features](./advanced-features.md)

213

214

## Error Handling

215

216

The library provides comprehensive error handling through the `telegram.error` module:

217

218

```python { .api }

219

class TelegramError(Exception):

220

"""Base class for all Telegram errors."""

221

def __init__(self, message: str): ...

222

223

class NetworkError(TelegramError):

224

"""Base class for exceptions due to networking errors."""

225

226

class BadRequest(NetworkError):

227

"""Raised when Telegram could not process the request correctly."""

228

229

class Forbidden(TelegramError):

230

"""Raised when the bot has not enough rights to perform the requested action."""

231

232

class TimedOut(NetworkError):

233

"""Raised when a request took too long to finish."""

234

235

class InvalidToken(TelegramError):

236

"""Raised when the token is invalid."""

237

238

class ChatMigrated(TelegramError):

239

"""Raised when group chat migrated to supergroup."""

240

def __init__(self, new_chat_id: int): ...

241

new_chat_id: int

242

243

class RetryAfter(TelegramError):

244

"""Raised when flood limits were exceeded."""

245

def __init__(self, retry_after: int): ...

246

retry_after: int

247

248

class Conflict(TelegramError):

249

"""Raised when a long poll or webhook conflicts with another one."""

250

251

class EndPointNotFound(TelegramError):

252

"""Raised when the requested endpoint is not found."""

253

254

class PassportDecryptionError(TelegramError):

255

"""Something went wrong with decryption."""

256

```

257

258

Common error handling patterns:

259

260

```python

261

from telegram.error import (

262

TelegramError, BadRequest, Forbidden, TimedOut,

263

NetworkError, ChatMigrated, RetryAfter

264

)

265

266

# Basic error handling

267

try:

268

await bot.send_message(chat_id, "Hello!")

269

except BadRequest as e:

270

print(f"Bad request: {e}")

271

except Forbidden as e:

272

print(f"Bot blocked or insufficient permissions: {e}")

273

except TimedOut as e:

274

print(f"Request timed out: {e}")

275

except NetworkError as e:

276

print(f"Network error: {e}")

277

except TelegramError as e:

278

print(f"Other Telegram error: {e}")

279

280

# Handling specific scenarios

281

try:

282

await bot.send_message(chat_id, "Hello!")

283

except ChatMigrated as e:

284

# Update chat_id and retry

285

new_chat_id = e.new_chat_id

286

await bot.send_message(new_chat_id, "Hello!")

287

except RetryAfter as e:

288

# Wait and retry

289

import asyncio

290

await asyncio.sleep(e.retry_after)

291

await bot.send_message(chat_id, "Hello!")

292

```

293

294

## Constants and Utilities

295

296

Access to all Telegram Bot API constants, limits, and utility functions:

297

298

```python

299

from telegram import constants

300

from telegram.helpers import escape_markdown, mention_html

301

302

# Constants

303

max_message_length = constants.MessageLimit.MAX_TEXT_LENGTH

304

parse_mode = constants.ParseMode.MARKDOWN_V2

305

306

# Helpers

307

escaped_text = escape_markdown("Text with *special* characters")

308

user_mention = mention_html(user.id, user.first_name)

309

```