🤖 telegroq
Give your Telegram bot a brain and a personality - in 5 lines of Python.
telegroq connects pyTelegramBotAPI (telebot) with the
blazing-fast Groq API. Write handlers with simple decorators, create
characters that remember each user, and let the library deal with rate limits, bad keys, long messages and
photos or stickers - so your bot keeps running no matter what.
import telegroq
bot = telegroq.createBot("TELEGRAM_BOT_TOKEN")
bot.set_groq_key("GROQ_API_KEY")
bot.auto_reply(telegroq.setCh("You are a witty, friendly assistant."))
bot.run()
That's a complete AI chatbot. 🎉
Unofficial project. Not affiliated with or endorsed by Telegram or Groq.
✨ Features
- 🎭 Characters with memory - a persona (system prompt) with per-user conversation history.
- ⚡ Groq-powered - fast answers from Llama and other models hosted on Groq.
- 🧩 Friendly decorators -
@bot.cmd,@bot.on_message,@bot.callback,@bot.on_error. - 🔘 Inline buttons made easy - keyboards and callbacks in a few lines.
- 💾 Pluggable storage - in-memory by default, SQLite built in, or bring your own.
- 🛡️ Never crashes on errors - rate limits, timeouts, bad keys and handler bugs are handled gracefully.
- ✂️ Smart sending - long replies are split automatically; broken Markdown/HTML falls back to plain text.
- 🧪 Typed and tested - ships with type hints (
py.typed) and a test suite that needs no network.
📦 Install
pip install telegroq
Requires Python 3.10+. You need a Telegram bot token from @BotFather and a Groq API key from console.groq.com.
🚀 Quickstart
import telegroq
bot = telegroq.createBot("123456:TELEGRAM_BOT_TOKEN")
bot.set_groq_key("gsk_...", model="llama-3.3-70b-versatile")
character = telegroq.setCh(
system_prompt="You are a funny, witty, and energetic AI assistant.",
max_history=10,
)
@bot.cmd("/start")
def start(user, msg):
bot.send_message(user.id, f"Hello {user.first_name}! I am ready.")
@bot.cmd("/reset")
def reset(user, msg):
character.clear_history(user.id)
bot.send_message(user.id, "Conversation memory cleared!")
@bot.on_message()
def chat(user, msg):
bot.reply(user.id, character.get_response(user.id, msg.text), message_id=msg.message_id)
bot.run()
Want it even shorter? Replace the chat handler with bot.auto_reply(character).
🔐 Keep secrets out of your code: read them from environment variables, as in
examples/main.py.
🧠 Core ideas
Handlers receive (user, msg)
useris telebot'sUser(.id,.username,.first_name, ...).msgis atelegroq.Message.msg.textis always a string (""for photos, stickers and voice notes),msg.argsis the text after a command,msg.chat_id/msg.is_privatedescribe the chat, andmsg.reply(text)answers in the chat the message came from. Everything else (msg.message_id,msg.caption,msg.photo, ...) is forwarded to the raw telebot message (msg.raw).
Groups:
bot.send_message(user.id, ...)writes to the user's private chat. In group chats usemsg.reply(...)orbot.send_message(msg.chat_id, ...). Restrict AI handlers with@bot.on_message(chat_types=["private"])if you do not want the bot to answer everything in a group.
Commands
@bot.cmd("/start", description="Say hello") # description appears in Telegram's command menu
@bot.cmd("help", "about") # several names, slash optional, any letter case
Registered commands are never delivered to @bot.on_message(), whatever order you declare them in.
🎭 Characters (personas with memory)
character = telegroq.setCh("You are a pirate.", max_history=10, temperature=0.9, model="llama-3.1-8b-instant")
character.get_response(user.id, "Hi!") # -> str (never raises on Groq errors)
character.ask(user.id, "Hi!") # -> Reply(text, ok, error_kind, error)
await character.aget_response(user.id, "Hi") # async variant (runs in a worker thread)
character.clear_history(user.id)
character.get_history(user.id)
- History is kept per user id and trimmed to the last
max_historymessages (0= stateless). Calls for the same user are serialised, so quick successive messages cannot scramble the conversation. system_promptmay also be a callable(user_id) -> strfor per-user prompts.extra_params={"top_p": 0.9}is forwarded tochat.completions.create.- Pass
client=to use your own Groq-compatible client, orbot=/.bind(bot)to pick which bot's key is used. Without either, the most recently configured key is used.
🔘 Inline buttons and callbacks
from telegroq import inline_keyboard
@bot.cmd("persona")
def choose(user, msg):
bot.send_message(msg.chat_id, "Who am I?", reply_markup=inline_keyboard(
[("Pirate", "persona:pirate"), ("Poet", "persona:poet")],
))
@bot.callback(prefix="persona:") # or @bot.callback("exact:data") / @bot.callback(regex=...)
def picked(user, call):
call.answer(f"OK, {call.args}!") # optional: telegroq answers for you if you don't
call.edit(f"Persona: {call.args}") # edit the message that holds the buttons
call is a CallbackContext with .data, .args (data after the prefix), .message, .answer(),
.edit(), .edit_keyboard() and .reply(). The button's loading spinner is cleared automatically.
button(text, callback_data) enforces Telegram's 64-byte limit; button(text, url=...) makes link buttons.
A complete persona-switching bot lives in
examples/persona_switcher.py.
💾 Persistent memory
from telegroq import SQLiteHistoryStore
character = telegroq.setCh("...", store=SQLiteHistoryStore("history.db"))
Implement telegroq.HistoryStore (load, save, clear) to use Redis, Postgres, etc. The default
MemoryHistoryStore forgets everything on restart.
🛡️ Errors never take the bot down
| Situation | What happens |
|---|---|
| Groq rate limit, bad key, timeout, outage | The user gets a friendly fallback message; the failed turn is not saved. Customise with setCh(..., fallbacks={"rate_limit": "..."}). |
| Your handler raises | The error is logged, the user gets bot.error_reply (or run your own @bot.on_error), polling continues. |
| Photo, sticker, voice note, ... | msg.text == ""; in private chats the user gets bot.non_text_reply unless you handle that type (@bot.on_message(content_types=["photo"])). Set it to None to stay silent. |
| Model output breaks Markdown/HTML | send_message(..., parse_mode=...) retries as plain text. |
| Reply longer than 4096 characters | Split into several messages automatically. |
| Network errors while polling | bot.run() keeps retrying. |
Forgetting set_groq_key raises telegroq.ConfigurationError - a setup bug, not a runtime failure.
📝 Logging
telegroq logs to the telegroq logger and is silent by default. Enable it with
logging.basicConfig(level=logging.INFO).
📚 API at a glance
telegroq.createBot(token, **telebot_kwargs) |
Create a TeleGroqBot (wraps telebot.TeleBot, available as bot.telebot; unknown attributes forward to it). |
bot.set_groq_key(api_key, model=...) |
Create the Groq client (timeout, max_retries optional). |
telegroq.setCh(system_prompt, max_history=10, **opts) |
Create a Character. |
@bot.cmd(*names, description=None, chat_types=None) |
Command handler fn(user, msg). |
@bot.on_message(content_types=None, chat_types=None, regexp=None, func=None, typing=True) |
Wildcard handler fn(user, msg). |
bot.auto_reply(character, ...) |
Answer every text message with a character. |
@bot.callback(*data, prefix=None, regex=None) |
Inline-button handler fn(user, call). |
@bot.on_error |
fn(exc, user, update) called when a handler raises. |
bot.send_message(user_id, text, **kw) / bot.reply(user_id, text, message_id=None, **kw) |
Sending helpers (splitting, plain-text retry). |
bot.run() / bot.stop() |
Start / stop long polling. |
telegroq.button, telegroq.inline_keyboard |
Keyboard helpers. |
HistoryStore, MemoryHistoryStore, SQLiteHistoryStore |
Conversation storage. |
Every public function and class has a docstring - try help(telegroq.Character).
🛠️ Development
git clone https://github.com/kkkik/telegroq && cd telegroq
python -m pip install -e ".[dev]"
pytest # no network or API keys needed (Telegram and Groq are faked)
ruff check .
Contributions and ideas are welcome - open an issue or a pull request.
📄 License
MIT - see LICENSE.
Metadata
Release files for telegroq 0.0.1
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| telegroq-0.0.1.tar.gz | 35.0 kB | Without provenance | Details for telegroq-0.0.1.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| telegroq-0.0.1-py3-none-any.whl | Python 3 | none | any | Details for telegroq-0.0.1-py3-none-any.whl |
Total release size: 59.7 kB
Release files / telegroq-0.0.1.tar.gz
| Download URL | telegroq-0.0.1.tar.gz |
|---|---|
| Size | 35.0 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
01ff193ae280acbcf025f841b22e58d9273a24e65e62a7ed89f3ca13f28a13ed
|
|
BLAKE2b-256 checksum How to use checksums |
01613f8f9de6e5ce741441a19a335cad1c8c7526f4936fed43a67d5cdf8ae48a
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
python-requests/2.34.2
|
Release files / telegroq-0.0.1-py3-none-any.whl
| Download URL | telegroq-0.0.1-py3-none-any.whl |
|---|---|
| Size | 24.7 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
0ec09c830d88f80b0d90de24696e194a5e35e45aa46651c27d9ac82680d1a691
|
|
BLAKE2b-256 checksum How to use checksums |
6ae14ddf061696a76a1b87ef657b4205c254fe4dfd982278d8c1afcf92336cd5
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
python-requests/2.34.2
|
Security for telegroq 0.0.1
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.