Orbeo DevОткрыть в Orbeo

⚡ How we made opening a chat 40× faster

This week we dug into why chats were slow to open. The culprit wasn't the network or the phone — it was the database access rules (Row Level Security in Postgres).

Before. The rule "only members can see a conversation's members" called a check function for every row. In a conversation with hundreds of people that's hundreds of calls per query: 117 ms.

After. The function now returns the whole set of the user's conversations, and the rule checks membership in it:

using (conversation_id in (select my_conversation_ids()))

Postgres evaluates that subquery once and matches rows against a hash table: 3 ms. Message search got the same treatment — from ~0.7 s down to 18 ms.

💡 Tips if you run Postgres or Supabase too:
• wrap calls inside policies in (select …) — even auth.uid(): user_id = (select auth.uid());
• run EXPLAIN ANALYZE as the real role (set role authenticated), not as an admin — admins bypass policies, so everything looks "fast";
• before swapping a policy, compare what every user sees before and after inside a transaction ending in rollback. We checked 635 accounts this way — not a single extra or missing row.

Questions — DM @orbeo_help.

#orbeodev #postgres #performance

⚡ Как мы ускорили открытие чата в 40 раз

На этой неделе разбирались, почему чат открывается с задержкой. Виновником оказалась не сеть и не телефон, а правила доступа в базе (Row Level Security в Postgres).

Что было. Правило «видеть участников беседы может только её участник» вызывало проверочную функцию для каждой строки. В беседе на сотни человек — сотни вызовов на один запрос: 117 мс.

Что стало. Функция теперь возвращает сразу множество бесед человека, а правило проверяет вхождение:

using (conversation_id in (select my_conversation_ids()))

Postgres считает такой подзапрос один раз и сверяет строки по хеш-таблице: 3 мс. Поиск по сообщениям тем же приёмом — с ~0,7 с до 18 мс.

💡 Совет, если у вас тоже Postgres или Supabase:
• оборачивайте вызовы в правилах в (select …) — даже auth.uid(): user_id = (select auth.uid());
• смотрите EXPLAIN ANALYZE от имени настоящей роли (set role authenticated), а не от админа — у админа правила не работают и всё «быстро»;
• перед заменой правила сравните, что видит каждый пользователь до и после, в транзакции с rollback. Мы так сверили 635 аккаунтов — ни одной лишней или пропавшей строки.

Вопросы — в личку @orbeo_help.

#orbeodev #postgres #performance

📎 Bots can now send files and videos

Until now sendDocument and sendVideo in the Orbeo Bot API returned an error: only photos and audio were accepted. Fixed as of November 6:

• sendDocument — any file: PDFs, archives, spreadsheets;
• sendVideo — videos with a cover and duration;
• the file_id from the response can be sent again without re-uploading;
• getFile returns a link the bot can use to download files sent to it.

Same as Telegram: aiogram and Telegraf code works unchanged.

🔒 Protected chats. When forwarding is disabled in a chat, messages arrive with has_protected_content: true, and copyMessage won't copy them (or view-once photos).

💡 Telegraf: end the server address with a slash — apiRoot: 'https://orbeo.me/botapi/'. Without it, requests go to the wrong place.

Questions — DM @orbeo_help.

#orbeodev #botapi

📎 Боты теперь отправляют файлы и видео

Раньше sendDocument и sendVideo в Bot API Orbeo отвечали ошибкой: принимались только фото и звук. С 6 ноября это починено:

• sendDocument — любые файлы: PDF, архивы, таблицы;
• sendVideo — ролики с обложкой и длительностью;
• file_id из ответа можно отправить снова, без повторной загрузки;
• getFile отдаёт ссылку, по которой бот скачивает присланный ему файл.

Всё как в Telegram: код на aiogram и Telegraf работает без правок.

🔒 Защищённые чаты. Если в беседе включён запрет пересылки, у сообщений приходит has_protected_content: true, а copyMessage такое сообщение (и «одноразовое» фото) не копирует.

💡 Telegraf: адрес сервера пишите со слешем на конце — apiRoot: 'https://orbeo.me/botapi/'. Без слеша запросы уходят мимо.

Вопросы — в личку @orbeo_help.

#orbeodev #botapi

orbeo-bot-starter.zip11,3 КБ · скачать в Orbeo

📦 Все файлы канала одним архивом · All files in one archive

Эхо-бот, aiogram, Telegraf, репост из Telegram, ИИ-автопостер, шпаргалка. · Echo bot, aiogram, Telegraf, Telegram mirror, AI autoposter, cheatsheet.

Вопросы и идеи для следующих постов — в личку @orbeo_help. · Questions and ideas for next posts — DM @orbeo_help.

🧠 AI writes the posts: store-api.com + an Orbeo bot

store-api.com gives you one key for Claude, GPT, Gemini and DeepSeek. The API is OpenAI-compatible, so any OpenAI code or SDK works.

The idea: a scheduled script asks a model to write a post → the bot publishes it to your channel.

curl https://store-api.com/v1/chat/completions \
  -H "Authorization: Bearer $STORE_API_KEY" \
  -H 'Content-Type: application/json' \
  -d '{"model":"anthropic/claude-haiku-4.5",
       "messages":[{"role":"user","content":"Write a post about ..."}]}'

The ready script below:
• your channel's topic and style live at the top of the file (TOPIC, STYLE);
• remembers past topics and doesn't repeat itself;
• one post per run, or --every 180 for every 3 hours (or cron).

Tips:
• cheap models are plenty for posts: Claude Haiku 4.5, Gemini Flash, DeepSeek;
• don't ask for “today's news” without a source — the model will make it up. Feed it RSS text instead;
• read the first few posts yourself and tune STYLE.

#guide #ai #storeapi

🧠 Посты пишет ИИ: store-api.com + бот Orbeo

store-api.com — один ключ к Claude, GPT, Gemini и DeepSeek, оплата в рублях. API как у OpenAI, поэтому подходит любой код и SDK для OpenAI.

Схема: скрипт по расписанию просит модель написать пост → бот публикует его в канал.

curl https://store-api.com/v1/chat/completions \
  -H "Authorization: Bearer $STORE_API_KEY" \
  -H 'Content-Type: application/json' \
  -d '{"model":"anthropic/claude-haiku-4.5",
       "messages":[{"role":"user","content":"Напиши пост про ..."}]}'

Готовый скрипт ниже:
• тема и стиль канала — в начале файла (TOPIC, STYLE);
• помнит прошлые темы и не повторяется;
• один пост — запуском, или --every 180 — каждые 3 часа (или cron).

Советы:
• для постов хватает недорогих моделей: Claude Haiku 4.5, Gemini Flash, DeepSeek;
• не просите «свежие новости» без источника — модель их выдумает. Для новостей подавайте ей текст из RSS;
• первые посты проверьте глазами и подкрутите STYLE.

#гайд #ии #storeapi

tg_to_orbeo_repost.py5,9 КБ · скачать в Orbeo

📎 Telegram → Orbeo: репост постов канала · channel mirror

TG_BOT_TOKEN=... ORBEO_BOT_TOKEN=... ORBEO_CHANNEL=@mychannel python3 tg_to_orbeo_repost.py

Необязательно · optional: TG_CHANNEL=@source — брать только из этого канала · only this channel; SIGNATURE="..." — подпись · footer.

🔁 Mirror your Telegram channel into Orbeo

Running a channel on Telegram? Let every new post appear on Orbeo too.

How it works:
1. Telegram: @BotFather → /newbot → token. Add that bot as an administrator of your Telegram channel — it then receives every post (channel_post).
2. Orbeo: create a bot and add it as an administrator of your Orbeo channel.
3. The script listens to Telegram and publishes to Orbeo: text with formatting (bold, links) and photos with captions.

TG_BOT_TOKEN=... ORBEO_BOT_TOKEN=... \
ORBEO_CHANNEL=@mychannel python3 tg_to_orbeo_repost.py

No dependencies, Python 3.8+. Keep it running on a server or your PC: systemd, pm2, screen. Optional SIGNATURE adds a line under every post.

⚠️ Only mirror channels you own or have permission to copy.

#guide #telegram #mirror

🔁 Репост из Telegram в Orbeo

Ведёте канал в Telegram? Пусть каждый новый пост сам появляется и в Orbeo.

Как устроено:
1. В Telegram: @BotFather → /newbot → токен. Добавьте этого бота администратором своего Telegram-канала — тогда он получает каждый пост (channel_post).
2. В Orbeo: создайте бота и добавьте его администратором своего канала Orbeo.
3. Скрипт слушает Telegram и публикует пост в Orbeo: текст с оформлением (жирный, ссылки), фото с подписью.

TG_BOT_TOKEN=... ORBEO_BOT_TOKEN=... \
ORBEO_CHANNEL=@mychannel python3 tg_to_orbeo_repost.py

Без библиотек, Python 3.8+. Держите его запущенным на сервере или ПК: systemd, pm2, screen. По желанию SIGNATURE — подпись под каждым постом.

⚠️ Копируйте только свои каналы или с разрешения автора.

#гайд #telegram #репост

📣 A bot that publishes to your channel

1. Create a bot (Settings → My bots).
2. Open your channel → header → Administrators → Add a bot → type the bot's handle. A bot can post to a channel only as an admin.
3. Send posts with chat_id = the channel handle:

import requests
TOKEN = "123:..."
requests.post(f"https://orbeo.me/botapi/bot{TOKEN}/sendMessage", json={
    "chat_id": "@mychannel",
    "text": "<b>News of the day</b>\nPost text",
    "parse_mode": "HTML",
    "reply_markup": {"inline_keyboard": [[{"text": "Read", "url": "https://orbeo.me"}]]},
})

Photos: sendPhoto with photo (a file or a URL) and caption.

Put it in cron or a systemd timer and the channel runs itself: exchange rates, weather, reports from your CRM, new products in your shop.

This very channel is posted by our bot @orbidevbot — the same way.

#guide #autoposting

📣 Бот, который сам публикует посты в канал

1. Создайте бота (Настройки → Мои боты).
2. Откройте свой канал → шапка → Администраторы → Добавить бота → введите адрес бота. Публиковать в канал бот может только администратором.
3. Отправляйте посты с chat_id = адрес канала:

import requests
TOKEN = "123:..."
requests.post(f"https://orbeo.me/botapi/bot{TOKEN}/sendMessage", json={
    "chat_id": "@mychannel",
    "text": "<b>Новость дня</b>\nТекст поста",
    "parse_mode": "HTML",
    "reply_markup": {"inline_keyboard": [[{"text": "Читать", "url": "https://orbeo.me"}]]},
})

Фото — sendPhoto с полем photo (файл или ссылка) и caption.

Поставьте скрипт в cron или systemd-таймер — и канал живёт сам: курсы валют, погода, сводки из вашей CRM, новые товары магазина.

Этот канал публикует наш бот @orbidevbot — тем же способом.

#гайд #автопостинг

📚 Telegram bot libraries work on Orbeo

Change only the server address — the rest of your code stays the same.

aiogram 3

session = AiohttpSession(api=TelegramAPIServer.from_base("https://orbeo.me/botapi"))
bot = Bot(TOKEN, session=session)

python-telegram-bot

Application.builder().token(TOKEN)
  .base_url("https://orbeo.me/botapi/bot")
  .base_file_url("https://orbeo.me/botapi/file/bot")

Telegraf — keep the trailing slash, otherwise Telegraf drops /botapi:

new Telegraf(TOKEN, { telegram: { apiRoot: 'https://orbeo.me/botapi/' } })

node-telegram-bot-api

new TelegramBot(TOKEN, { polling: true, baseApiUrl: 'https://orbeo.me/botapi' })

Supported: text and photos, inline and reply keyboards, commands, editing and deleting, polls, inline mode “@bot query”, groups and channels.

Limits: 30 messages/s per bot, 1/s per DM, 20/min per group — beyond that you get 429 with retry_after.

Below: two ready bots, on aiogram and on Telegraf.

#guide #aiogram #telegraf

📚 Готовые библиотеки Telegram работают в Orbeo

Меняете только адрес сервера — остальной код остаётся как был.

aiogram 3

session = AiohttpSession(api=TelegramAPIServer.from_base("https://orbeo.me/botapi"))
bot = Bot(TOKEN, session=session)

python-telegram-bot

Application.builder().token(TOKEN)
  .base_url("https://orbeo.me/botapi/bot")
  .base_file_url("https://orbeo.me/botapi/file/bot")

Telegraf — косая черта в конце обязательна, иначе Telegraf отрежет /botapi:

new Telegraf(TOKEN, { telegram: { apiRoot: 'https://orbeo.me/botapi/' } })

node-telegram-bot-api

new TelegramBot(TOKEN, { polling: true, baseApiUrl: 'https://orbeo.me/botapi' })

Работают текст и фото, кнопки под сообщением и вместо клавиатуры, команды, правка и удаление, опросы, встроенный режим «@бот запрос», группы и каналы.

Лимиты: 30 сообщений в секунду на бота, 1 в секунду в одну личку, 20 в минуту в группу — сверх них сервер ответит 429 с retry_after.

Ниже два готовых бота: на aiogram и на Telegraf.

#гайд #aiogram #telegraf

orbeo_echo_bot.py3 КБ · скачать в Orbeo

📎 Эхо-бот без библиотек · Echo bot, no dependencies

ORBEO_BOT_TOKEN=123:... python3 orbeo_echo_bot.py

Отвечает на /start и /help, повторяет текст, сам ставит меню команд. · Answers /start and /help, echoes text, sets the command menu.

⚡ Bot API: your first requests

Server address: https://orbeo.me/botapi. Same protocol as the Telegram Bot API — same methods, same fields, same errors.

T=123:your_token
curl https://orbeo.me/botapi/bot$T/getMe

curl -X POST https://orbeo.me/botapi/bot$T/sendMessage \
  -H 'Content-Type: application/json' \
  -d '{"chat_id":"@mychannel","text":"Hello from the API!"}'

• Every response is {"ok": true, "result": …} or {"ok": false, "description": …}.
• chat_id: in a DM use chat.id from the update; in groups and channels — "@handle".
• Incoming messages: getUpdates (long polling up to 50 s) or setWebhook (https only).

Below: an echo bot in plain Python — zero dependencies, one command to run.

#guide #api

orbeo.me · мессенджер без номера телефона