Skip to content

Conversation

Copy link

Copilot AI commented Sep 22, 2025

Problem

The ban system was unusable for administrators because it required an internal database ID that only exists in the application's database. Administrators only know users by their Telegram ID or username (@handle), making it impossible to ban or unban users effectively.

Before this fix:

Admin: Нужно забанить пользователя @problematic_user
Bot: Введите id пользователя, которого необходимо забанить:
Admin: 987654321  // Telegram ID
Bot: Пользователя с таким id не существует.
Admin: @problematic_user  // Username
Bot: Неверный ввод, введите число.

Solution

Enhanced the ban/unban validators to accept multiple identifier formats and automatically resolve them to the internal database ID:

  • Telegram ID (e.g., 987654321) - what administrators commonly have
  • Username (e.g., @username) - user-friendly identifier
  • Internal database ID (e.g., 123) - backward compatibility maintained
  • Explicit internal ID (e.g., db:123) - for collision disambiguation

After this fix:

Admin: 987654321
Bot: Валидация пройдена. Найден пользователь по Telegram ID: Alice Smith

Admin: @problematic_user  
Bot: Валидация пройдена. Найден пользователь с username @problematic_user: Bob Johnson

Admin: 123  // When collision exists
Bot: ⚠️ ВНИМАНИЕ: ID 123 найден у двух пользователей! 
     Выбран по Telegram ID: Diana Prince.
     Для точности используйте @username или db:123

Implementation Details

New resolve_user_input_to_db_id() function

  • Intelligently detects input type (numeric ID, @username, db: prefix)
  • Queries the database to find the corresponding user
  • Detects ID collisions when internal DB ID matches Telegram ID of different users
  • Smart prioritization: Telegram ID is preferred in collision cases
  • Returns the internal database ID for downstream processing
  • Provides descriptive feedback about which user was found

Enhanced validators

  • Both ban_validator() and unban_validator() now use flexible input resolution
  • Maintains backward compatibility with existing internal ID usage
  • Automatically converts validated input to internal database ID
  • Improved error messages with context about the user lookup
  • Collision warnings alert admins to ambiguous cases with guidance

Updated admin interface

  • Clear prompts explaining all accepted input formats with examples
  • Collision guidance explains db: prefix for disambiguation
  • Better user guidance reduces confusion for administrators

ID Collision Handling

  • Automatic detection when same number exists as both internal ID and Telegram ID
  • Prioritizes Telegram ID in collision cases (more likely admin intent)
  • Explicit disambiguation using db:123 prefix for internal ID specification
  • Clear warnings inform admins about collisions with resolution guidance

Testing

The implementation handles various edge cases:

  • Whitespace around input ( @username )
  • Non-existent users with appropriate error messages
  • Already banned/unbanned users with clear feedback
  • Invalid input formats with helpful guidance
  • Empty usernames and other edge cases
  • ID collision scenarios with proper detection and resolution
  • Explicit disambiguation using db: prefix format

All existing functionality remains unchanged - this is a pure enhancement that makes the ban system actually usable while maintaining full backward compatibility and handling potential ID conflicts intelligently.

Fixes the core issue where administrators couldn't effectively manage user bans due to requiring internal database identifiers that they don't have access to, while also resolving potential ambiguity when IDs collide between internal database and Telegram ID spaces.


💡 You can make Copilot smarter by setting up custom instructions, customizing its development environment and configuring Model Context Protocol (MCP) servers. Learn more Copilot coding agent tips in the docs.

@github-actions
Copy link

💩 Code linting failed, use black and isort to fix it.

Copilot AI and others added 2 commits September 22, 2025 08:54
Co-authored-by: MarkShidran <15670678+MarkShidran@users.noreply.github.com>
Co-authored-by: MarkShidran <15670678+MarkShidran@users.noreply.github.com>
Copilot AI changed the title [WIP] Изучи репозиторий бота и сделай так, чтобы функционал "бана" пользователей работал. А то он пока не работает и я не могу исключать участник... Fix ban functionality to accept Telegram ID and username instead of requiring internal database ID Sep 22, 2025
Copilot AI requested a review from MarkShidran September 22, 2025 08:57
Copy link

@Wudext Wudext left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

че за пиздец, ладно аппруваю

@Wudext Wudext marked this pull request as ready for review September 22, 2025 09:41
@github-actions
Copy link

💩 Code linting failed, use black and isort to fix it.

1 similar comment
@github-actions
Copy link

💩 Code linting failed, use black and isort to fix it.

Copy link
Member

@MarkShidran MarkShidran left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

А как ты учитываешь возможность того, что ID в базе и ID в Telegram совпадут?
@copilot

…ambiguation

Co-authored-by: MarkShidran <15670678+MarkShidran@users.noreply.github.com>
Copy link
Author

Copilot AI commented Sep 22, 2025

А как ты учитываешь возможность того, что ID в базе и ID в Telegram совпадут?
@copilot

Отличный вопрос! Ты абсолютно прав - коллизия ID была серьезной проблемой в первоначальной реализации.

Проблема была в том, что:

User A: DB_ID=123, TG_ID=987654321, Name="Charlie"  
User B: DB_ID=456, TG_ID=123, Name="Diana"
Admin: 123 → Старая логика: находила Charlie (неверно!)

Исправление (commit 5d1be30):

Детектирование коллизий - одновременная проверка обоих типов ID
Умный приоритет - при коллизии выбирается пользователь по Telegram ID (чаще всего это намерение админа)
Явное разрешение - добавлен префикс db:123 для точного указания внутреннего ID
Предупреждения - админ получает четкое уведомление о коллизии

Теперь:

Admin: 123
Bot: ⚠️ ВНИМАНИЕ: ID 123 найден у двух пользователей! 
     Выбран по Telegram ID: Diana.
     Для точности используйте @username или db:123

Для точности:

Admin: db:123  
Bot: Найден пользователь по внутреннему ID: Charlie

Проблема полностью решена с автоматическим детектированием и механизмами disambiguation.

Copilot AI changed the title Fix ban functionality to accept Telegram ID and username instead of requiring internal database ID Fix ban functionality to accept Telegram ID and username with collision detection Sep 22, 2025
Copilot AI requested a review from MarkShidran September 22, 2025 09:50
@MarkShidran MarkShidran merged commit d2d0578 into main Sep 27, 2025
0 of 2 checks passed
@MarkShidran MarkShidran deleted the copilot/fix-142d4adc-0389-484f-bf4b-7aecef7c32d2 branch September 27, 2025 21:15
@github-actions
Copy link

💩 Code linting failed, use black and isort to fix it.

1 similar comment
@github-actions
Copy link

💩 Code linting failed, use black and isort to fix it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants