multiple user ids for bot api

This commit is contained in:
kulikov0 committed 2026-05-09 19:57:00 +02:00
1 parent 870118d5ab
commit 31d03bcb14
8 files changed
+59 -44

No files matched your search

+2 -2
View File
@@ -68,8 +68,8 @@
<input type="text" id="vkToken" placeholder="vk1.a.xxx...">
<label for="vkGroupId">Group ID</label>
<input type="number" id="vkGroupId" placeholder="123456789">
<label for="vkUserId">User ID</label>
<input type="number" id="vkUserId" placeholder="123456789">
<label for="vkUserId">User IDs (comma-separated)</label>
<input type="text" id="vkUserId" placeholder="123456789, 987654321">
<div class="popup-buttons">
<button class="btn-cancel" id="btnSettingsCancel">Cancel</button>
<button class="btn-save" id="btnSettingsSave">Save</button>
+2 -1
View File
@@ -27,7 +27,8 @@
var check = setInterval(function() {
var url = location.href;
if (url.indexOf(CALL_PATH_MARKER) !== -1) {
console.log("[BOT] Telemost: call link:", url);
var tabId = window.__CALL_CHECKER_TAB_ID || '';
console.log("[BOT] Telemost[" + tabId + "]: call link:", url);
window.__CALL_LINK__ = url;
clearInterval(check);
}
+2 -1
View File
@@ -35,7 +35,8 @@
var captureLink = function(link) {
if (window.__CALL_LINK_CAPTURED__) return;
console.log("[BOT] VKCalls: call link:", link);
var tabId = window.__CALL_CHECKER_TAB_ID || '';
console.log("[BOT] VKCalls[" + tabId + "]: call link:", link);
window.__CALL_LINK__ = link;
window.__CALL_LINK_CAPTURED__ = true;
};
+5 -1
View File
@@ -151,7 +151,11 @@ export class BotManager {
console.log('[BOT] Message from', fromId, ':', text, 'payload:', payload);
if (this.settings.userId && fromId.toString() !== this.settings.userId.toString()) {
const allowedIds = this.settings.userId
.split(',')
.map((id) => id.trim())
.filter((id) => id.length > 0);
if (allowedIds.length > 0 && !allowedIds.includes(fromId.toString())) {
return;
}
-9
View File
@@ -152,15 +152,6 @@ export class TabManager {
return this.callStatusCache.get(tabId) || CallStatus.Inactive;
}
findBotPeerId(platform: Platform): number | null {
for (const [tabId, tab] of this.tabs) {
if (this.botTabIds.has(tabId) && tab.platform === platform && tab.peerId != null) {
return tab.peerId;
}
}
return null;
}
getTabList(): TabListEntry[] {
const result: TabListEntry[] = [];
this.tabs.forEach((tab, tabId) => {
+19 -19
View File
@@ -31,10 +31,12 @@ function parseCallStatus(msg: string): { tabId: string; status: CallStatus } | n
};
}
function extractCallLink(msg: string, prefix: string): string | null {
const idx = msg.indexOf(prefix);
if (idx === -1) return null;
return msg.split(prefix)[1].trim();
function extractTaggedCallLink(msg: string, platform: Platform): { tabId: string; link: string } | null {
const tag = platform === Platform.Telemost ? 'Telemost' : 'VKCalls';
const re = new RegExp('\\[BOT\\] ' + tag + '\\[([^\\]]*)\\]: call link:\\s*(.+)$');
const match = msg.match(re);
if (!match) return null;
return { tabId: match[1].trim(), link: match[2].trim() };
}
export function createWindow(tabManager: TabManager): BrowserWindow {
@@ -97,8 +99,8 @@ export function createWindow(tabManager: TabManager): BrowserWindow {
if (ac) ac.vk.kickDisconnected();
}
handleBotCallLink(tabManager, msg, Platform.VK, '[BOT] VKCalls: call link:');
handleBotCallLink(tabManager, msg, Platform.Telemost, '[BOT] Telemost: call link:');
handleBotCallLink(tabManager, msg, Platform.VK);
handleBotCallLink(tabManager, msg, Platform.Telemost);
const callStatus = parseCallStatus(msg);
if (callStatus) {
@@ -120,18 +122,16 @@ export function createWindow(tabManager: TabManager): BrowserWindow {
return win;
}
function handleBotCallLink(
tabManager: TabManager,
msg: string,
platform: Platform,
prefix: string,
): void {
const link = extractCallLink(msg, prefix);
if (!link) return;
console.log(`[MAIN] ${platform} call link captured:`, link);
const peerId = tabManager.findBotPeerId(platform);
if (peerId != null && tabManager.botManager) {
console.log(`[MAIN] Sending ${platform} link to peer:`, peerId);
tabManager.botManager.sendMessage(peerId, `Call created!\n ${link}`);
function handleBotCallLink(tabManager: TabManager, msg: string, platform: Platform): void {
const tagged = extractTaggedCallLink(msg, platform);
if (!tagged) return;
const tab = tabManager.getTab(tagged.tabId);
if (!tab || tab.peerId == null) {
console.log(`[MAIN] ${platform} call link captured but no peer for tab ${tagged.tabId}`);
return;
}
console.log(`[MAIN] Sending ${platform} link to peer ${tab.peerId} (tab ${tagged.tabId}):`, tagged.link);
if (tabManager.botManager) {
tabManager.botManager.sendMessage(tab.peerId, `Call created!\n${tagged.link}`);
}
}
+6 -6
View File
@@ -152,9 +152,9 @@
![ID сообщества](res/community_id.png)
8. Узнайте свой VK ID (профиль -> "Управление аккаунтом VK ID" -> "Мои данные")
8. Узнайте свой VK ID (профиль -> "Управление аккаунтом VK ID" -> "Мои данные"). Чтобы разрешить нескольким пользователям, перечислите ID через запятую (например `12345,67890`).
9. Заполните настройки бота в Creator: Token, Group ID, User ID. Сохраните и включите бота.
9. Заполните настройки бота в Creator: Token, Group ID, User IDs (через запятую). Сохраните и включите бота. Бот игнорирует команды от пользователей не из списка.
![Настройки бота в Creator](res/bot_config.png)
@@ -197,7 +197,7 @@ Standalone Go-бинарник `headless-vk-bot` - то же самое, что
./headless-vk-bot \
--token <community_access_token> \
--group-id <community_id> \
--user-id <your_vk_id> \
--user-id <vk_id_1>,<vk_id_2> \
--bins-dir /usr/local/bin \
--vk-cookies /etc/whitelist-bypass/cookies-vk.json \
--tm-cookies /etc/whitelist-bypass/cookies-yandex.json
@@ -209,13 +209,13 @@ Standalone Go-бинарник `headless-vk-bot` - то же самое, что
|---|---|
| `--token <str>` | Community access token (обязательно) |
| `--group-id <id>` | ID сообщества, только цифры (обязательно) |
| `--user-id <id>` | VK ID пользователя, которому разрешено отправлять команды. Пусто = разрешено всем (НЕ рекомендуется) |
| `--user-id <ids>` | Список VK ID через запятую (`12345,67890`), которым разрешено отправлять команды. Пусто = разрешено всем (НЕ рекомендуется) |
| `--bins-dir <dir>` | Папка, где лежат `headless-vk-creator` / `headless-telemost-creator` / `headless-wbstream-creator` (обязательно) |
| `--vk-cookies <path>` | Путь к VK куки (нужен для `/vk`) |
| `--tm-cookies <path>` | Путь к Yandex куки (нужен для `/tm`) |
| `--sessions-dir <dir>` | Папка для логов спавненных creators. Опционально - без флага логи не пишутся, stdout/stderr creators отбрасываются |
При получении команды бот спавнит соответствующий creator с `--write-file <tmp>`, ждёт появления линка в файле (до 60 секунд) и присылает его в чат. Если вы укажете `--user-id`, команды от других пользователей будут проигнорированы.
При получении команды бот спавнит соответствующий creator с `--write-file <tmp>`, ждёт появления линка в файле (до 60 секунд) и присылает его в чат. `--user-id` принимает список через запятую; если указан, команды от пользователей не из списка игнорируются.
### Запуск как systemd-сервис
@@ -231,7 +231,7 @@ Type=simple
ExecStart=/usr/local/bin/headless-vk-bot \
--token <community_access_token> \
--group-id <community_id> \
--user-id <your_vk_id> \
--user-id <vk_id_1>,<vk_id_2> \
--bins-dir /usr/local/bin \
--vk-cookies /etc/whitelist-bypass/cookies-vk.json \
--tm-cookies /etc/whitelist-bypass/cookies-yandex.json
+23 -5
View File
@@ -59,7 +59,7 @@ type session struct {
type bot struct {
token string
groupID string
userID string
userIDs []string
binsDir string
vkCookies string
tmCookies string
@@ -165,8 +165,18 @@ func (b *bot) poll() error {
}
func (b *bot) handleMessage(peerID, fromID int64, text, payload string) {
if b.userID != "" && fmt.Sprint(fromID) != b.userID {
return
if len(b.userIDs) > 0 {
from := fmt.Sprint(fromID)
allowed := false
for _, id := range b.userIDs {
if id == from {
allowed = true
break
}
}
if !allowed {
return
}
}
log.Printf("[bot] msg from=%d peer=%d text=%q payload=%q", fromID, peerID, text, payload)
@@ -395,7 +405,7 @@ func (b *bot) run() error {
func main() {
token := flag.String("token", "", "VK community access token (required)")
groupID := flag.String("group-id", "", "VK community ID, digits only (required)")
userID := flag.String("user-id", "", "VK user ID allowed to issue commands (optional, empty = anyone)")
userID := flag.String("user-id", "", "comma-separated VK user IDs allowed to issue commands (empty = anyone)")
binsDir := flag.String("bins-dir", "", "directory containing headless-*-creator binaries (required)")
vkCookies := flag.String("vk-cookies", "", "path to VK cookies JSON")
tmCookies := flag.String("tm-cookies", "", "path to Yandex cookies JSON for Telemost")
@@ -406,8 +416,16 @@ func main() {
log.Fatal("--token, --group-id, --bins-dir are required")
}
var allowedUsers []string
for _, id := range strings.Split(*userID, ",") {
trimmed := strings.TrimSpace(id)
if trimmed != "" {
allowedUsers = append(allowedUsers, trimmed)
}
}
b := &bot{
token: *token, groupID: *groupID, userID: *userID,
token: *token, groupID: *groupID, userIDs: allowedUsers,
binsDir: *binsDir, vkCookies: *vkCookies, tmCookies: *tmCookies,
sessionsDir: *sessionsDir,
sessions: map[string]*session{},