--формирование имени пользователя
local getFirstLastName = function(fName,lName,uName)
local res = ""
if fName ~= nil and lName ~= nil then
res = fName.." "..lName
else
if fName ~= nil then
res = fName
else
res = lName
end
end
if uName ~= nil then
if res ~= nil and res ~= "" then
res = res.." @"..uName
else
res = "@"..uName
end
end
return res
end
--запрос в БД, возвращает скалярное значение либо nil
local getSQLScalarValue = function(query,params,varName)
local res
if query == '' or query == nil then
res = nil
return res
end
if varName == '' or varName == nil then
res = nil
return res
end
res = SQL:query(query,params)
if res[1] == nil then
res = nil
return res
else
res = res[1][varName]
return res
end
end
--найти пользователя 1Формы по его нику в Telegram
local getUserIdByTelegramId = function(tlgUserID)
local res = getSQLScalarValue(
[[
;with cte as (
select cast(@TlgUserID as varchar(max)) TlgUserID
)
select isnull(u.UserID,-1) fromUserID
from cte
left join Users u on u.ICQ = cte.TlgUserID
]],
{
TlgUserID = tlgUserID
},
"fromUserID"
)
return res
end
--Удалить из чата 1ф
local removeSubscriber = function(chatTaskID,userID,delUserID,commentText)
local doNotWriteComment = false
if commentText == nil or commentText == '' then
doNotWriteComment = true
end
SMART:execute_action("RemoveSubscriber", chatTaskID, "task",
{
Task = chatTaskID,
DeletingUser = userID,
UserToDelete = delUserID,
Reason = commentText,
DoNotWriteComment = doNotWriteComment
}
)
end
--добавить в подписчики, если не подписан
local addToSubscribers = function(sysUserID,taskID,userID)
local SubscriberIsExists
SubscriberIsExists = getSQLScalarValue(
[[
select 1 IsExists
from dbo.fn_cm_GetSubScribersOnTask(@chatTaskID)
where UserID = @fromUserID
]],
{
chatTaskID = taskID,
fromUserID = userID
},
"IsExists"
)
--если не подписан к чату
if SubscriberIsExists ~= 1 then
--добавить в подписчики
SMART:execute_action("AddSubscriber", taskID, "task", {
Who = sysUserID, --кто добавляет
Whom = userID, --кого добавить
Task = taskID, --куда добавить
DoNotWriteComment = true --не писать комментарий
})
end
return
end
local addComment = function(taskID,userID,commentText,isQuestion)
SMART:execute_action("PostComment", taskID, "task",
{
CommentAuthor = userID,
CommentText = commentText,
Recipients = nil,
RecipCopies = nil,
CommentType = 3,
Task = taskID,
ForcedEmail = false,
CommentSMS = false,
TextAsHTML = false,
NoSubscription = false,
MarkAsQuestion = isQuestion,
CommentVisibleOnlyToRealRecipients = false
})
end
local addFile = function(taskID,userID,link,commentText,fileName)
SMART:execute_action("DownloadFile", taskID, "task",
{
Task = taskID,
UploadingUserName = userID,
TargetExternalParameter = nil,
FileLink = link,
Comment = commentText,
DownloadManyFiles = false,
FileMask = nil,
FileCreateDateFrom = nil,
FileCreateDateTo = nil,
FileName = fileName
})
end
local createChatTask = function(ChatName,tlgChatID,UserIDs)
local res = SMART:execute_action("CreateTask", nil, "task",
{
Owner = systemUserID,
Subcat = systemChatSubcatID,
TaskText = ChatName,
CreateLink = false,
CreateSubtask = false,
Performers = nil,
DueTime = nil,
TaskStartTime = nil,
ExtParams = nil,
NewTaskCopySubscribers = false,
CreateCopyFiles = false,
CopyParentText = false,
Priority = 1,
Notify = nil,
UsersToSubscribe = UserIDs,
CreateCopiesForEachPerformer = false,
LinkFiles = nil,
AssignLetterWithTask = nil,
Confidentiality = nil,
LinkAsUser = nil
})
if res ~= nil then
SQL:query(
[[
insert cm_Telegram_ChatToTask
select cast(@tlgChatID as varchar(20)), @TaskChatID
]],
{
tlgChatID = tlgChatID,
TaskChatID = res[0]
}
)
end
return res
end
systemUserID = getSQLScalarValue("select top 1 SystemRobotID from Settings where CustomerID = 1",{},"SystemRobotID") --Системный пользователь
systemChatSubcatID = getSQLScalarValue("select top 1 ChatSubcatID from settings",{},"ChatSubcatID") --Категория чатов
local bot = {}
bot.id = "tlgChatBot"
bot.token = "tlgToken"
bot.host = "api.telegram.org"
bot.getURL = function(methodName)
local res
local h = "https://"
if methodName == nil or methodName == "" then
return nil
end
local case = {
["getFile"] = function()
local resCase = h..bot.host.."/bot"..bot.id..":"..bot.token.."/getFile"
return resCase
end,
["getMe"] = function()
local resCase = h..bot.host.."/bot"..bot.id..":"..bot.token.."/getMe"
return resCase
end,
["file"] = function()
local resCase = h..bot.host.."/file/bot"..bot.id..":"..bot.token
return resCase
end
}
res = case[methodName]()
return res
end
local getFile = function(fileId)
local res = nil
local reqParams = {}
reqParams.method = "GET"
reqParams.url = bot.getURL("getFile")
reqParams.parameters = {file_id = fileId}
reqParams.headers = {ContentType = "application/json"}
reqParams.rawBody = {}
local req = HTTP:send_http_request(
reqParams.method,
reqParams.url,
reqParams.parameters,
reqParams.headers,
UTILS:json_encode(reqParams.rawBody)
)
local response = UTILS:json_decode(req["HttpResponse"]["ResponseContent"])
if response["ok"] then
local file = {}
file.url = bot.getURL("file")
file.path = response["result"]["file_path"]
res = file.url.."/"..file.path
end
return res
end
local params = UTILS:json_decode(EVENTPARAMS["PublishedObjectParameters"])
local chatBotUserID = 1fChatUserID --UserId бота, от которого приходят сообщения, если пользователь не идентифицирован в 1f
local tlgUserID = params["requestBody"]["message"]["from"]["id"] --id пользователя в telegram
local tlgReplyUserID
if params["requestBody"]["message"]["reply_to_message"] ~= nil then
tlgReplyUserID = params["requestBody"]["message"]["reply_to_message"]["from"]["id"] --id пользователя кому отвечает автор
end
local tlgCaption = params["requestBody"]["message"]["caption"] --Подпись к файлу, документу
local tlgFileId = getSQLScalarValue("select top 1 json_value([value],'$.file_id') FileID from openjson(@json,'$.requestBody.message.photo') order by iif([key] = 0,'10',[key])",{json = EVENTPARAMS["PublishedObjectParameters"]},"FileID")
local tlgFileName
if tlgFileId == nil then
tlgFileId = params["requestBody"]["message"]["document"]
if tlgFileId ~= nil then
tlgFileId = params["requestBody"]["message"]["document"]["file_id"]
tlgFileName = params["requestBody"]["message"]["document"]["file_name"]
end
end
local tlgChatId = params["requestBody"]["message"]["chat"]["id"] --id группы в telegram
local tlgChatName = params["requestBody"]["message"]["chat"]["title"] --Название группы в telegram
local tlgMessageText = params["requestBody"]["message"]["text"] --текст сообщения
if tlgMessageText == '' then
tlgMessageText = nil
end
local isQuestion = false
local tlgAddUserID = nil --UserID пользователя, которого добавили в чата
local tlgDelUserID = nil --UserID пользователя, которого удалили из чата
local leftMemberId = nil
if params["requestBody"]["message"]["left_chat_participant"] ~= nil then
leftMemberId = params["requestBody"]["message"]["left_chat_participant"]["id"]
end
if params["requestBody"]["message"]["left_chat_member"] ~= nil then
leftMemberId = params["requestBody"]["message"]["left_chat_member"]["id"]
end
if leftMemberId ~= nil then
tlgDelUserID = getSQLScalarValue(
[[
;with cte as (
select cast(@TlgUserID as varchar(max)) TlgUserID
)
select isnull(u.UserID,-1) LeftUserID
from cte
left join Users u on u.ICQ = cte.TlgUserID
]],
{
TlgUserID = leftMemberId
},
"LeftUserID"
)
if tlgDelUserID == -1 then
tlgDelUserID = nil
end
end
--Имя в telegram
local tlgFirstLastName = getFirstLastName(
params["requestBody"]["message"]["from"]["first_name"],
params["requestBody"]["message"]["from"]["last_name"],
params["requestBody"]["message"]["from"]["username"] --Ник в telegram
)
--UserID в 1f, от имени которого будет сформировано сообщение в 1f чатах
local fromUserID = getSQLScalarValue(
[[
;with cte as (
select cast(@TlgUserID as varchar(max)) TlgUserID
)
select isnull(u.UserID,@ChatBotUserID) fromUserID
from cte
left join Users u on u.ICQ = cte.TlgUserID
]],
{
TlgUserID = tlgUserID,
ChatBotUserID = chatBotUserID
},
"fromUserID"
)
if fromUserID == chatBotUserID then
if tlgMessageText ~= nil then
tlgMessageText = "["..tlgFirstLastName.." ("..tlgUserID..")".."]: "..tlgMessageText
end
end
--Задача чата в 1f
local chatTaskID = getSQLScalarValue(
[[
select TaskID
from cm_vw_ChatToTask
where ChatID = @tlgChatId
]],
{tlgChatId = tlgChatId},
"TaskID"
)
--если задачу чата не нашли, то создадим новую задачу
if chatTaskID == nil then
local res = createChatTask(tlgChatName,tlgChatId,{fromUserID})
if res ~= nil then
chatTaskID = res[0]
end
else
if tlgDelUserID ~= nil then
removeSubscriber(chatTaskID,fromUserID,tlgDelUserID)
end
end
local addMemberId = nil
if params["requestBody"]["message"]["new_chat_member"] ~= nil then
addMemberId = params["requestBody"]["message"]["new_chat_member"]["id"]
end
if params["requestBody"]["message"]["new_chat_participant"] ~= nil then
addMemberId = params["requestBody"]["message"]["new_chat_participant"]["id"]
end
if addMemberId ~= nil then
tlgAddUserID = getUserIdByTelegramId(addMemberId)
if tlgAddUserID > 0 then
addToSubscribers(systemUserID,chatTaskID,tlgAddUserID)
end
end
--есть кто отправляет и есть что отправить
if fromUserID ~= nil then
--подписываем пользователя к задаче (к чату) если он не подписан
addToSubscribers(systemUserID,chatTaskID,fromUserID)
--входящий JSON
if chatTaskID == defchatTaskID then
addComment(chatTaskID,fromUserID,EVENTPARAMS["PublishedObjectParameters"],isQuestion)
end
if tlgMessageText ~= nil then
--отправляем сообщение
addComment(chatTaskID,fromUserID,tlgMessageText,isQuestion)
end
if tlgFileId ~= nil then
local filePath = getFile(tlgFileId)
addFile(chatTaskID,fromUserID,filePath,"testComment",tlgFileName)
if tlgCaption ~= nil then
addComment(chatTaskID,fromUserID,tlgCaption,isQuestion)
end
end
end
RESULT = true;
|