{
  "name": "10 Telegram task assignments to Arena Tasks",
  "nodes": [
    {
      "parameters": {
        "rule": {
          "interval": [
            {
              "field": "seconds",
              "secondsInterval": 30
            }
          ]
        }
      },
      "id": "b5e2cccf-fcce-4685-8d7a-61aa0da3c389",
      "name": "Poll Tasks & Reminders",
      "type": "n8n-nodes-base.scheduleTrigger",
      "typeVersion": 1.2,
      "position": [
        240,
        300
      ],
      "notes": "هر ۱۵ ثانیه getUpdates",
      "notesInFlow": true
    },
    {
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "// n8n Code node; run once for all items. Owns Telegram getUpdates polling.\nconst C = {\n  TELEGRAM_BOT_TOKEN: '', // Set locally, never share the token\n  NOTION_TOKEN: '', // Set locally\n  TASKS_DB: 'Arena Tasks',\n  TELEGRAM_PROXY: 'http://127.0.0.1:12334',\n  NOTION_PROXY: 'http://127.0.0.1:12334',\n  GROUP_ID: '', // Recommended: numeric Telegram group ID (usually negative)\n  H01: '76156046', H02: '5868631014', H03: '7848957609',\n  REMINDER_HOURS: 2,\n};\nfunction env(k) { try { return String($env[k] || ''); } catch { return ''; } }\nconst TG = C.TELEGRAM_BOT_TOKEN || env('TELEGRAM_BOT_TOKEN');\nconst NT = C.NOTION_TOKEN || env('NOTION_TOKEN');\nif (!TG || !NT) throw new Error('Set TELEGRAM_BOT_TOKEN and NOTION_TOKEN locally in this node.');\nconst sd = $getWorkflowStaticData('global');\nif (!Array.isArray(sd.pending)) sd.pending = [];\nconst tgbase = 'https://api.telegram.org/bot' + TG;\nconst notionbase = 'https://api.notion.com/v1';\nconst headers = {Authorization:'Bearer '+NT, 'Notion-Version':'2022-06-28', 'Content-Type':'application/json'};\nconst tx = (opts) => this.helpers.httpRequest({...opts, ...(C.TELEGRAM_PROXY ? {proxy:C.TELEGRAM_PROXY}:{}), json:true, timeout:30000});\nconst nx = (opts) => this.helpers.httpRequest({...opts, ...(C.NOTION_PROXY ? {proxy:C.NOTION_PROXY}:{}), headers, json:true, timeout:30000});\nconst esc = s => String(s).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/\"/g,'&quot;');\nconst send = (id,text) => tx({method:'POST',url:tgbase+'/sendMessage',body:{chat_id:id,text,parse_mode:'HTML',disable_web_page_preview:true}});\nconst results=[];\n// Search using Notion's legacy database API (2022-06-28); database must be shared with integration.\nlet dbId=sd.dbId;\nasync function db() {\n  if (dbId) return dbId;\n  const wanted=String(C.TASKS_DB).trim();\n  if (/^[a-f0-9-]{32,36}$/i.test(wanted)) return dbId=wanted;\n  const r=await nx({method:'POST',url:notionbase+'/search',body:{query:wanted,filter:{property:'object',value:'database'},page_size:100}});\n  const matches=(r.results||[]).filter(x=>x.object==='database' && (x.title||[]).map(t=>t.plain_text||'').join('').trim().toLowerCase()===wanted.toLowerCase());\n  if (matches.length!==1) throw new Error('Expected exactly one shared Notion database named '+wanted+'; found '+matches.length+'. Share it with integration or set its database ID.');\n  return dbId=matches[0].id;\n}\nasync function createTask(chatId,from,code,description) {\n  const id=await db();\n  const title='@'+code.toLowerCase()+' '+description.slice(0,120);\n  const r=await nx({method:'POST',url:notionbase+'/pages',body:{parent:{database_id:id},properties:{Name:{title:[{text:{content:title}}]},Status:{select:{name:code.startsWith('AG')?'New':'Waiting'}}},children:[{object:'block',type:'paragraph',paragraph:{rich_text:[{type:'text',text:{content:description.slice(0,1900)}}]}},{object:'block',type:'paragraph',paragraph:{rich_text:[{type:'text',text:{content:'Telegram chat: '+chatId+'; requester: '+from+'; assignee: '+code}}]}}]}});\n  return r.id;\n}\n// Reminders checked on every schedule tick, even when Telegram has no new messages.\nfor (const p of [...sd.pending]) {\n  if (Date.now()<p.due) continue;\n  try {\n    const page=await nx({method:'GET',url:notionbase+'/pages/'+encodeURIComponent(p.page)});\n    const status=page.properties && page.properties.Status;\n    const value=status && ((status.select&&status.select.name)||(status.status&&status.status.name));\n    if (value==='Done') { sd.pending=sd.pending.filter(x=>x.page!==p.page); continue; }\n    await send(p.person,'⏰ یادآوری وظیفه '+esc(p.code)+'\\n'+esc(p.text)+'\\nشناسه: <code>'+esc(p.page)+'</code>\\nبرای اتمام در گروه: /done '+esc(p.page));\n    sd.pending=sd.pending.filter(x=>x.page!==p.page);\n    results.push({kind:'reminder',code:p.code,page:p.page});\n  } catch(e) { results.push({kind:'reminder_error',code:p.code,error:'Check private chat permission, Hiddify and Notion connectivity.'}); }\n}\n// Telegram getUpdates is exclusive: disable old workflow 07 and any webhook for this bot.\nlet updates;\ntry { updates=await tx({method:'GET',url:tgbase+'/getUpdates',qs:{offset:Number(sd.offset||0),timeout:0,allowed_updates:JSON.stringify(['message'])}}); }\ncatch(e) { throw new Error('Telegram getUpdates failed (check Hiddify, token, and that old 07/webhook are disabled): '+String(e.message||e).replace(new RegExp(TG.replace(/[.*+?^${}()|[\\]\\\\]/g,'\\\\$&'),'g'),'[REDACTED]').slice(0,220)); }\nfor (const u of (updates.result||[])) {\n  sd.offset=u.update_id+1; // persist before side effects to prevent duplicate page creation\n  const m=u.message||{};const chat=m.chat||{};const text=String(m.text||'').trim();\n  if (!chat.id || m.from?.is_bot || !['group','supergroup'].includes(chat.type)) continue;\n  if (C.GROUP_ID && String(chat.id)!==String(C.GROUP_ID)) continue;\n  const done=text.match(/^\\/done(?:@\\w+)?\\s+([a-f0-9-]{32,36})\\s*$/i);\n  if (done) {\n    const p=sd.pending.find(x=>x.page.replace(/-/g,'')===done[1].replace(/-/g,''));\n    if (!p) { await send(chat.id,'این شناسه در فهرست کارهای انسانیِ باز نیست.'); continue; }\n    if (String(m.from.id)!==String(p.person) && String(m.from.id)!==String(p.requester)) { await send(chat.id,'فقط مسئول یا درخواست‌دهنده می‌تواند این کار را ببندد.');continue; }\n    try { await nx({method:'PATCH',url:notionbase+'/pages/'+p.page,body:{properties:{Status:{select:{name:'Done'}}}}});sd.pending=sd.pending.filter(x=>x.page!==p.page);await send(chat.id,'✅ کار '+esc(p.code)+' انجام شد.'); }\n    catch(e) { await send(chat.id,'ثبت انجام کار در Notion ناموفق بود؛ دوباره امتحان کنید.'); }\n    continue;\n  }\n  if (!/^\\/task(?:@\\w+)?(?:\\s|$)/i.test(text)) continue;\n  const match=text.match(/^\\/task(?:@\\w+)?\\s+@(ag0?[1-9]|h0?[1-3])\\s+([\\s\\S]{1,1800})$/i);\n  if (!match) {await send(chat.id,'فرمت: /task @ag01 متن وظیفه  یا  /task @h01 متن وظیفه\\nهر دستور یک مسئول دارد.');continue;}\n  const code=match[1].toUpperCase().replace(/^AG([1-9])$/,'AG0$1').replace(/^H([1-3])$/,'H0$1');\n  const description=match[2].trim();if (!description) {await send(chat.id,'متن وظیفه خالی است.');continue;}\n  try {\n    const id=await createTask(chat.id,m.from.id,code,description);\n    if (code.startsWith('H')) {\n      const person=C[code];\n      if (!/^\\d+$/.test(String(person||''))) throw new Error('Missing Telegram user ID for '+code);\n      const mention='<a href=\"tg://user?id='+person+'\">'+esc(code)+'</a>';\n      await send(chat.id,'📌 وظیفه برای '+mention+' ثبت شد:\\n'+esc(description)+'\\nشناسه: <code>'+esc(id)+'</code>\\nپس از انجام: /done '+esc(id));\n      sd.pending.push({page:id,person:String(person),code,text:description,requester:String(m.from.id),due:Date.now()+Number(C.REMINDER_HOURS)*3600000});\n    } else await send(chat.id,'📌 کار '+esc(code)+' در Arena Tasks ثبت شد. اجرای ایجنت به workflow 08 سپرده می‌شود.');\n    results.push({kind:'created',code,page:id});\n  } catch(e) {await send(chat.id,'ثبت کار ناموفق بود. اتصال Notion، نام دیتابیس و نوع ستون‌ها را بررسی کنید.'); results.push({kind:'create_error',code,error:'Check Notion database schema, sharing, tokens and Hiddify.'});}\n}\nreturn [{json:{processed:results.length,results,pending:sd.pending.length,offset:sd.offset||0}}];\n"
      },
      "id": "b5fea0cb-75f5-4344-94e3-539caf8276f3",
      "name": "Telegram /task → Notion + human reminders",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        520,
        300
      ]
    }
  ],
  "connections": {
    "Poll Tasks & Reminders": {
      "main": [
        [
          {
            "node": "Telegram /task → Notion + human reminders",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "settings": {
    "executionOrder": "v1"
  },
  "active": false,
  "pinData": {},
  "meta": {
    "templateCredsSetupCompleted": true
  }
}