- Python 99.5%
- Dockerfile 0.5%
| Filename | Latest commit message | Latest commit date |
|---|---|---|
| .woodpecker | ||
| data | ||
| telegram_bot | ||
| tests | ||
| tools | ||
| .dockerignore | ||
| .gitignore | ||
| .python-version | ||
| config.toml | ||
| Dockerfile | ||
| pyproject.toml | ||
| README.md | ||
| renovate.json | ||
| uv.lock | ||
Telegram inline size and percentage bot
Size and percentage generators with three-hour sizes and configurable percentage
timers, private range
preferences, and group matching.
Type the bot's username in any Telegram chat and select Share your size 🍌.
It posts My cock size is 15cm 😊 or a negative result such as
My cock size is -5cm 🌀.
Mixed mode chooses positive and negative results equally. Conditional on the selected sign, band weights are 80%, 15%, and 5%:
| Sign | 80% band | 15% band | 5% band |
|---|---|---|---|
| Positive | 1–15cm | 16–20cm | 21–30cm |
| Negative | −1 to −10cm | −11 to −15cm | −16 to −20cm |
Each integer inside the selected band has equal odds. Zero is excluded. Private positive-only and negative-only preferences retain their sign and use the same magnitude weights. These are operator-chosen novelty weights, not measured anatomical statistics.
Set [results].size_negative_percent (integer 0–100), size_positive_weights,
and size_negative_weights in the operator TOML. Each weight array contains
three nonnegative integers totaling 100, in the band order shown above. A zero
weight disables that band for new draws. Existing cached results, history and
three-hour expiry are preserved when weights change.
The first request generates a result. That result remains the same across chats for three hours; requesting again does not extend the timer. The first request after expiry draws again, and can coincidentally produce the same number.
Percentage and group matching
Inline results offer both size and a random 0–100% percentage, including both
endpoints with equal odds. Use @your_bot gay or the percentage Share button
for just the percentage. Each user's percentage has its own configurable timer
(three hours by default),
independent of their size result and range preference. These scores are for fun
and do not measure or infer anyone's orientation.
Add the bot to a group and share your percentage inline, or send /gay@your_bot.
To request someone else's score, use /gay @username or /size @username,
including /gay@your_bot @username. Usernames are matched case-insensitively
against identities already observed by the bot. Unknown or ambiguous usernames
produce a short error; they never silently return your own score. You can also
use a Telegram user mention or reply to the person's message with /gay or
/size, including people without usernames. An explicit target takes precedence
over the reply. Bot and anonymous reply targets are rejected.
Targeted requests use that person's existing cache, configured expiry and private size range preference. Expired or missing results are generated for the target. In groups, successful replies count as the target's shared scores for rankings and percentage matching, including their partner cooldown. Private lookups do not enter any group. Replies mention the target and use the normal auto-deletion policy. Logs retain both the requesting and targeted user IDs. Each share registers its issued score and checks up to ten users for any pair of your and their scores shared in that group within the configured lookback totaling 100%. Inline shares automatically post a notification when matches exist; no-match shares stay quiet. Commands include matches in their response. Each match lists both scores and their sharing timestamps in UTC. Matching is enabled by default. Inline query previews do not enroll anyone: the actual group message must arrive via this bot, verified against its numeric ID returned by Telegram getMe. Only a previously issued score that was unexpired at the original Telegram sharing time is accepted. Delayed delivery preserves that original time. Copied, forwarded, expired-at-sharing, wrong-bot and unissued scores do not enroll users. The bot must belong to the group to receive inline messages; group privacy mode can remain enabled. Forum replies stay in the requesting topic; the match pool is scoped to the group. Names in bot result and match replies are clickable Telegram mentions, including users without usernames. The lower score of the matched historical pair is labeled top and the higher score bottom; 50/50 pairs are shown as ties. No private notifications are sent. Group /size replies name the requester, like /gay. Compact default messages reduce group clutter; extended sharing times remain available through own_time and other_time template placeholders. Forwarded and anonymous-admin commands do not enroll users.
Matching is enabled by default and controlled only by the operator’s TOML configuration. There are no personal matching toggles, commands or callbacks. Legacy per-user preferences are retained as unused database records; they no longer affect enrollment or searches. Private size preferences remain available. Multiple historical scores can be considered if the lookback exceeds the score timer; each user appears once, using the newest qualifying historical pair. Old participation is pruned after seven days. Already posted messages remain in Telegram after expiry.
Operator configuration
Edit config.toml and restart the bot:
[matching]
enabled = true
lookback_hours = 24
Set matching.enabled = false to disable group enrollment and notifications
operator-wide; restart/reconcile after editing. Existing shared history remains
stored and can qualify again when matching is enabled. The default is on, with a
24-hour window. Fractional hours are supported, from one second up to
168 hours (seven days). The window uses the last time each score was explicitly
shared inline or via /gay in the group, not when the random score was first generated.
Sharing again refreshes participation, but never resets the score's three-hour
timer. Both participants’ scores may be historical and remain eligible until
their sharing times fall outside the window, even if both people have rerolled.
For example, a 40% score shared at 07:00 can match a 60% score shared at 11:00,
even if the first person has since drawn 80%. A new share triggers the check.
The bot does not periodically announce pairs or retrieve old Telegram messages.
Set BOT_CONFIG to the absolute path of a different TOML file if needed. The
container uses /app/config.toml; mount a replacement read-only there. Local
runs below use the checked-in file. Invalid settings stop startup with a sanitized
error. Configuration is operator-wide; matching is controlled exclusively by
this configuration.
Editable result messages
The same TOML file accepts these plain-text templates:
[messages]
size = "My cock size is {value}cm {emoji}"
group_result = "{name}: {result}"
percentage = "🌈 I am {value}% gay!"
match_intro = "🌈 Matches for {name}:"
match_heading = "💞 Matches (100%):"
match_line = "{roles} ({own_value}% + {other_value}%)"
match_roles = "{top_name} is a top, {bottom_name} is a bottom."
match_tie = "{own_name} and {other_name} are tied at 50%."
no_match = "No matches yet."
Omitted keys use defaults. Percentage must contain {value} exactly once;
role and prefix fields accept the placeholders illustrated above; match_line also
accepts own_name, other_name, own_time, other_time, top_name, bottom_name,
top_value and bottom_value (no_match also
accepts {hours}). Use {{ and }} for literal braces. Format conversions,
attribute lookups and unknown placeholders are rejected at startup, as are
individual templates exceeding the response length budget. Long match lists
are split at Telegram’s UTF-16 length limit, preserving the originating topic.
Configured percentage wording
also drives verification of inline shares. Previously posted messages using old
wording are not reinterpreted after changing the template.
For the root deployment, edit the botConfig TOML block in
/Users/yaelmeya/git/m0sh1.cc/infra/root/apps/telegram-bot/values.yaml, bump
/Users/yaelmeya/git/m0sh1.cc/infra/root/apps/telegram-bot/Chart.yaml, and use
the usual GitOps flow. A ConfigMap checksum rolls the pod automatically after ArgoCD
syncs the change; a new application image is unnecessary. The application's
/Users/yaelmeya/git/m0sh1.cc/telegram-bot/config.toml supplies local/image defaults.
Automatic group reply cleanup
[cleanup]
delete_after_seconds = 60
match_delete_after_seconds = 1800
Ordinary replies default to one minute. Replies containing matches and automatic
inline-match announcements default to 30 minutes; set match_delete_after_seconds
to 900 for 15 minutes, or 0 to keep those messages. Rankings use their own timer.
Setting delete_after_seconds to 0 pauses all non-ranking cleanup. Allowed
values are integer seconds
from 0 to 86400. Only message IDs returned from this bot’s successful group
sendMessage responses are scheduled. User commands, user inline shares and
private bot replies are untouched. Existing messages sent before cleanup was
deployed are not retroactively scheduled. Timers survive restarts in SQLite.
Transient failures retry; missing messages finish quietly; permission failures
are logged and removed from the queue. Messages aged 48 hours are skipped.
Polling wakes for the next deletion deadline; API/network delays can postpone
cleanup. Stored results, names and history are retained. With cleanup paused,
already queued tasks remain and resume when enabled. Newly sent replies use the
configured delay; changing it does not reschedule existing queued replies.
Private commands
/startand/help: instructions, data-storage notice, and a Share button./settings: choose Mixed, Negative-only, or Positive-only privately./gay: show your current percentage privately, without joining a group match pool.
Preferences do not infer gender and are never included in shared messages. Changing mode preserves an unexpired result if its sign is still allowed; otherwise the next request generates a compatible result. Existing shared messages are never edited by a preference change.
Run locally
Use uv with Python 3.14. Runtime code has no third-party dependencies;
uv_build is pinned as the packaging backend.
uv sync --locked
uv run --locked python -m unittest discover -s tests -v
Provide TELEGRAM_BOT_TOKEN through your secret manager or runtime environment,
without putting it in command arguments, source files, or Git. Then run:
BOT_CONFIG="$PWD/config.toml" \
DATABASE_PATH="$PWD/data/telegram-bot.sqlite" \
uv run --locked python -m telegram_bot
DATABASE_PATH defaults to /data/telegram-bot.sqlite. HEALTH_PATH defaults
to /tmp/telegram-bot-health. The process responds to SIGTERM/SIGINT, locks its
database against concurrent local instances, and resumes the stored update
offset after restart. It checks BotFather inline mode and existing webhooks on
startup. It also refreshes the default Telegram command menu so removed matching
toggles no longer appear. A webhook conflict is reported without deleting it.
Telegram setup
Register a bot with BotFather, enable inline queries with /setinline, and use
a placeholder such as Share size or percentage. Configure /start, /help,
/settings, /size, and /gay as bot commands. Keep group
privacy enabled. Inline use needs no group membership; group matching requires
adding the bot. Percentage shares via that bot trigger matching automatically;
/gay@your_bot is also supported. Old Telegram messages cannot be retrieved
retroactively; participants must share again after the feature is deployed.
Long polling connects outbound to https://api.telegram.org. The bot needs
outbound DNS and HTTPS, without a public webhook or website endpoint.
Container and root01 deployment
The Dockerfile uses a verified, version-tagged dhi.io/python:3.14.7-alpine3.24
runtime. A version-tagged dhi.io/uv:0.12.23-debian13-dev build stage creates a
pure-Python wheel; CI uses the same uv development image. The build stage may
download its Python interpreter and pinned packaging backend. The deployed image
contains no uv, build interpreter, or build dependencies. It needs no
shell or package manager at runtime and runs as UID/GID 65532. Mount durable
storage at /data, provide writable temporary storage at /tmp, and use a
read-only root filesystem. The data directory must be writable by UID/GID 65532.
docker build --platform linux/amd64 -t telegram-bot:test .
Run health probes directly as python3 -m telegram_bot.health. The marker is
fresh after successful startup/polling and expires after 180 seconds. Deploy one
replica with a strategy that prevents overlapping pollers. SQLite persistence
preserves preferences, unexpired results, names, history, and update progress.
Woodpecker validates pull requests without publication credentials. Main-branch
publishing follows the private Forgejo registry convention, producing immutable
commit tags and a mutable main tag. Publication needs the existing secret
names forgejo_package_username, forgejo_package_token, dhi_username, and
dhi_password enabled for this repository; values never belong in the pipeline.
The publishing workflow also requires the pinned Docker Buildx plugin to be
permitted by the CI administrator. PR validation runs in a separate workflow
without privileged access. Use the published image digest in the root01 Helm
wrapper.
Cluster resources belong in the infrastructure repository. Enable the prepared
wrapper only after the image and root SealedSecret are available. Reconcile
through Git and ArgoCD. The token Secret is named telegram-bot with key
TELEGRAM_BOT_TOKEN; create it through the root SealedSecrets workflow.
Stored data and privacy
SQLite stores numeric Telegram user IDs, latest display names, optional usernames,
preferences, and active results. result_history stores each generated
number, timestamps, and the name/username supplied at generation time. Cached
requests do not duplicate history. Names can change; the numeric ID identifies
the user. History is retained across restarts and is available to the operator
through the database; the bot does not expose history publicly.
percentage_history stores percentage generations with the same name snapshots
and timestamps. group_percentages stores group IDs and names/scores explicitly
shared inline or through /gay for matching, with their last sharing time.
Schema version 2
adds percentage tables. Schema version 3 shortens active size expiry to three
hours from original generation time, preserving old history with its original
six-hour expiry. Schema version 4 likewise shortens active percentage expiry to
three hours, preserving old percentage history and group participation. It adds
persistent group message receipts to suppress repeat notifications after a
successfully handled share. A crash between Telegram accepting a response and
committing its receipt can still repeat a notification; delivery is not atomic.
Schema version 5 adds persisted bot-reply deletion jobs. Preferences and update
progress are preserved.
History records generation, not proof that an inline result was posted. Message
contents,
gender, and tokens are not stored. Container logs are single-line JSON on stdout
at INFO level. They include startup/shutdown, every polling cycle (including idle
cycles), update processing, commands and inline selections, names/usernames and
user/chat IDs, generated/cached values and expiry times, preference changes,
group participation, matching lookback and matched users/scores, successful API
responses, ignored requests, retries, and sanitized failures. Tokens, raw request
or response bodies, arbitrary message text, and token-bearing URLs are never
logged. Log storage contains personal data and needs the same access controls as
SQLite. Inspect it with kubectl --context root -n apps logs deployment/telegram-bot --timestamps --follow or the container log view in k9s. Backups need the same access
controls. To remove a user's records, contact the bot operator.
Use SQLite's online backup API for consistent live backups, including WAL data. Root01's existing SQLite-export and local-volume archive workflow can carry the database off-host once configured. PVC retention alone is not backup or restore proof.
Group rankings
Use /ranking in a group for four lists: five largest positive sizes,
five most negative sizes (−20 before −1), five highest percentages, and five
lowest percentages. /ranking size shows both size sections; /ranking gay
shows both percentage sections. Each section includes a person once with their
average of distinct results shared in that group during the last 24 hours.
Percentages use one average per person; positive and negative sizes are averaged
separately so they do not cancel each other. Each generated result is counted
once, even when re-shared repeatedly; separate draws of the same value count
separately. Averages display one decimal place and rank by the unrounded value.
The same person can appear in both size sections. For percentages, the high and
low lists show the same per-person averages in opposite order; in small groups
a person can appear in both lists. Empty
sections say there are no shared scores. Ties share a rank; user ID breaks ties
at the entry limit. Manual ranking names are plain text; automatic posts include participant mentions. Ranking requests
never draw results or reset timers. Private scores and other groups are excluded.
The [ranking] section of config.toml controls enabled, layout
(extremes by default, or highest for the original descending lists), limit
(entries per section, 1–10; default 5), lookback_hours (up to 168), and
score_mode (average by default, best for historical extrema, or latest
for each person's latest qualifying share in each section). Size sections select their sign
before selecting each person's score. automatic_enabled, interval_hours
(default 12), and delete_after_seconds (default 1800; zero keeps ranking posts)
control delivery. targets explicitly lists {chat_id = <negative group ID>}
objects; add thread_id = <positive topic ID> for a forum topic. Empty targets
mean no automatic posts. Rankings pool verified shares across group topics.
The four section headings are editable as ranking_size_positive_heading,
ranking_size_negative_heading, ranking_percentage_high_heading, and
ranking_percentage_low_heading under [messages], using {limit}, {hours}, and {metric} (averages or scores).
Existing size/percentage row templates and the empty message apply to all sections.
Ranking mode changes affect presentation only; individual scores, their cache
expiry, result history, and exact-total matching remain unchanged.
[results].percentage_step = 1 draws whole percentages from 0 through 100.
percentage_weights = [40, 40, 20] gives 40% of new draws to 0–30%,
40% to 31–69%, and 20% to 70–100%, with uniform selection inside each band.
The expected score is 43%; rankings continue to average distinct generated
results shared in that group. Weights must be three nonnegative integers totaling
100, ordered low/middle/high. Omitting weights retains uniform grid draws.
A positive-weight band must contain a value on the configured grid.
[matching].tolerance_percent = 10 qualifies historical pairs totaling
90–110%, inclusive, for both announcements and /matches. Set it to 0 for
exact 100% matching. Lower score is top, higher is bottom; equal scores are verse.
Message templates can use {total} for the actual sum and {value} in
match_tie. The 24-hour partner lock remains unchanged. Existing scores keep
their original expiry; new draws use percentage_cooldown_hours (default 3).
First automatic posting is one interval after a target is enabled. The database persists deadlines through restarts. Changing the interval resets the next posting to one new interval from configuration loading. After downtime the bot sends at most one overdue ranking per target and starts the next interval; it does not replay every missed post. Empty rankings skip automatic posting. Manual requests do not alter the automatic schedule. Split automatic rankings keep a durable snapshot and sent-chunk progress, so retries and restarts resume only the remaining chunks. Command results count as shared only after their reply succeeds; verified inline shares already count as public participation. Permanent send errors are logged and the next interval proceeds; transient failures use normal retry backoff. Telegram sends cannot guarantee exactly-once delivery if a connection or process fails after Telegram accepts a message but before the bot records it.
Ranking replies use their own persistent deletion policy, independently of
normal group replies. Headings, rows and empty-list wording are controlled by
ranking_size_heading, ranking_percentage_heading, ranking_size_row,
ranking_percentage_row, and ranking_empty in [messages]. Heading fields
accept {limit} and {hours}; rows accept {rank}, {name} and {value}.
Keep {name} to include the participant name. Schema 6 adds group size
shares and ranking schedules and preserves prior history and deletion jobs.
Percentage recalculation timer
[results]
percentage_cooldown_hours = 3
The default is three hours; fractional hours are allowed, from one second
(1/3600 hours, expressed as a decimal) to seven days (168 hours).
The first request after expiry draws a new percentage. Repeated requests do not
extend the timer. Configuration changes apply to newly generated results;
already issued results retain their stored expiry. Size results remain at three
hours, and matching lookback and ranking intervals have separate settings.
Schema 7 allows variable percentage lifetimes while preserving existing results,
names, history, group participation, queued deletions and ranking schedules.
Production uses the operator TOML in
/Users/yaelmeya/git/m0sh1.cc/infra/root/apps/telegram-bot/values.yaml
under botConfig, mounted at /config/config.toml.
PostgreSQL / CNPG
The production backend is PostgreSQL. SQLite remains an explicit compatibility backend during the migration acceptance window; there is no fallback or dual write. All identities, preferences, result histories, caches, group shares, receipts, update offsets, ranking schedules/outbox chunks and deletion queues move together. JSON operational logs still go to container stdout.
[database]
backend = "postgres"
host = "cnpg-main-rw.apps.svc.cluster.local"
port = 5432
name = "telegram_bot"
user = "telegram_bot"
password_file = "/secrets/postgres/password"
sslmode = "verify-full"
sslrootcert = "/certs/postgres/ca.crt"
connect_timeout_seconds = 5
statement_timeout_seconds = 10
lock_timeout_seconds = 5
Use the direct CNPG read/write Service, since the session advisory singleton
lock cannot work through a transaction-mode pooler. Every Telegram request
after getMe checks the same original database session's lock. Database or
lock loss removes readiness and exits; restart must acquire the lock again.
Database errors and credentials are sanitized. An ambiguous Telegram send
cannot be guaranteed exactly once; offset and durable sent-chunk markers
only advance after the corresponding operation succeeds.
Run the complete suite against an isolated PostgreSQL 18 database whose name
ends in _test:
TEST_DATABASE_URL=postgresql://postgres@localhost:5432/telegram_bot_test \
uv run --locked python tools/run_tests.py tests
Tests deliberately reset that test database's public schema. Missing PostgreSQL
fails CI. Image builds separately run tools/run_tests.py tests --unit under
the actual DHI Alpine interpreter. The wheelhouse uses CPython 3.14 musl wheels
and hashes from uv.lock; Debian virtual environments are never transplanted.
Migration and rollback
Migration tooling has no Telegram token or API calls. The CLI requires the nonsecret bot ID to acquire the same singleton as the runtime. PostgreSQL schema creation happens only in the migration job; runtime startup verifies its version/checksum and the imported offset.
- Publish the compatible image while production remains explicitly SQLite. Prepare the dedicated sealed role credential, retained Database, TLS mounts, narrow egress and prune-protected legacy/artifact PVCs through GitOps.
- Commit/sync
maintenance.enabled=true, retaining the SQLite configuration. Verify the old pod has exited and there are no writers before enabling any migration job. The chart's maintenance gate alone cannot prove this. - In a separate commit, enable the revisioned migration Job with
mode=import. It snapshots the stable source database and WAL privately, checks SQLite schema 7/integrity/foreign keys, imports all 13 tables atomically, resets history identity sequences and verifies counts plus canonical row hashes. Snapshot and reports remain on the protected artifact PVC. Source files stay untouched and mounted read-only. No names/rows appear in reports. - Require a completed, verified import before changing
botConfigto the PostgreSQL settings above,postgres.enabled=true, maintenance off and the migration Job disabled. This removes the bot's writable SQLite mount. Check Ready/Synced/Healthy, offset/cache continuity and normal user activity. - Complete a native backup and isolated restore, verify data, queues and an automatic ranking cycle. Retain the original database and artifacts for at least seven days plus acceptance; removal is a separate reviewed release.
CLI equivalents (use a secure PostgreSQL config file; never a password in a DSN):
python3 -m telegram_bot.migrate import --bot-id 8994768239 \
--config /config/config.toml --source /legacy/telegram-bot.sqlite \
--destination /migration/run-snapshot.sqlite --report /migration/import.json
python3 -m telegram_bot.migrate verify --bot-id 8994768239 \
--config /config/config.toml --source /migration/run-snapshot.sqlite \
--report /migration/verify.json
python3 -m telegram_bot.migrate export-sqlite --bot-id 8994768239 \
--config /config/config.toml --destination /migration/current-export.sqlite \
--report /migration/export.json
Reimporting the same unchanged source is verification-only. Different sources, changed imported state, nonempty targets and existing export destinations fail closed. Rollback after PostgreSQL writes must freeze the bot and export its current repeatable-read state to a new, verified SQLite artifact, including the latest offset/receipts/queues. Restore that artifact with a reviewed Argo-managed job before reactivating the SQLite-compatible backend. Never reactivate the stale pre-cutover file after new PostgreSQL writes. If PostgreSQL is unavailable, recover it before attempting a lossless rollback.
Group match history
Use /matches in a group to list its ten newest qualifying historical pairs.
Each pair of people appears once, using its newest qualifying shared scores
within [matching].lookback_hours (24 hours by default). Both scores must be
inside that window; other groups and the requester’s identity do not affect
the list. This lists qualifying pairs, rather than an archive of announcements,
and does not generate new scores.
Replies mention both people, show each historical score and sharing time in
Europe/Berlin, and assign the lower percentage as top and higher as bottom.
Equal scores use the configurable tie message. Nonempty lists use
[cleanup].match_delete_after_seconds; empty lists use normal group cleanup.
Edit [messages].matches_list_heading, matches_list_line, and
matches_list_empty in config.toml to change the output. The line accepts
{own_name}, {own_value}, {own_time}, {other_name}, {other_value},
{other_time}, {roles}, {top_name}, {top_value}, {bottom_name}, and
{bottom_value}. The heading accepts {limit} and {hours}, and the empty
message accepts {hours}. Private chats receive instructions to use the
command in a group. Operator-disabled matching also disables this command.
Partner assignments and compact replies
matching.partner_cooldown_hours = 24 gives each participant one assigned
partner per group for a rolling 24 hours. The first eligible historical pair
locks both participants; subsequent requests still return their score without
repeating the match. 0 disables this assignment lock. /matches always lists
the ten newest possible historical pairs, including assigned participants.
Assignments are persisted in CNPG. Reservations survive transient send failures and retries; permanent Telegram failures cancel a pending reservation. Telegram acknowledgement loss may still repeat the same notice.
Editable match_line and matches_list_line templates accept {own_role} and
{other_role} (lower percentage top, higher bottom, equal verse). List timestamps
use UTC HH:MM; state UTC once in the heading. For example:
Suis 15% (top, 19:23) ↔ Manat 85% (bottom, 16:03).
ranking_heading states the period and metric once, above the four sections.
Release 0.4.6 requires PostgreSQL schema version 2. Stop the poller through the
GitOps maintenance gate, then run the revisioned migration Job with
mode=upgrade-schema, using the new image. This adds the checksummed assignment
ledger without changing existing scores. Verify Job completion and schema before
resuming the bot. Runtime does not create or upgrade schema. SQLite exports now
use schema 8; migration still accepts legacy schema 7 snapshots.
Manual ranking names are plain text and do not create user mention entities. Automatic ranking posts include clickable participant mentions, including those saved in durable delivery snapshots. Result replies and matches also retain clickable participant mentions.