commands.go 35 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183
  1. // mautrix-whatsapp - A Matrix-WhatsApp puppeting bridge.
  2. // Copyright (C) 2021 Tulir Asokan
  3. //
  4. // This program is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Affero General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // This program is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Affero General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Affero General Public License
  15. // along with this program. If not, see <https://www.gnu.org/licenses/>.
  16. package main
  17. import (
  18. "context"
  19. "encoding/json"
  20. "errors"
  21. "fmt"
  22. "html"
  23. "math"
  24. "regexp"
  25. "sort"
  26. "strconv"
  27. "strings"
  28. "time"
  29. "github.com/skip2/go-qrcode"
  30. "github.com/tidwall/gjson"
  31. "go.mau.fi/whatsmeow"
  32. "go.mau.fi/whatsmeow/appstate"
  33. "go.mau.fi/whatsmeow/types"
  34. "maunium.net/go/mautrix"
  35. "maunium.net/go/mautrix/bridge"
  36. "maunium.net/go/mautrix/bridge/commands"
  37. "maunium.net/go/mautrix/bridge/status"
  38. "maunium.net/go/mautrix/event"
  39. "maunium.net/go/mautrix/id"
  40. )
  41. type WrappedCommandEvent struct {
  42. *commands.Event
  43. Bridge *WABridge
  44. User *User
  45. Portal *Portal
  46. }
  47. func (br *WABridge) RegisterCommands() {
  48. proc := br.CommandProcessor.(*commands.Processor)
  49. proc.AddHandlers(
  50. cmdSetRelay,
  51. cmdUnsetRelay,
  52. cmdInviteLink,
  53. cmdResolveLink,
  54. cmdJoin,
  55. cmdAccept,
  56. cmdCreate,
  57. cmdLogin,
  58. cmdLogout,
  59. cmdTogglePresence,
  60. cmdDeleteSession,
  61. cmdReconnect,
  62. cmdDisconnect,
  63. cmdPing,
  64. cmdDeletePortal,
  65. cmdDeleteAllPortals,
  66. cmdList,
  67. cmdSearch,
  68. cmdOpen,
  69. cmdPM,
  70. cmdSync,
  71. cmdDisappearingTimer,
  72. )
  73. }
  74. func wrapCommand(handler func(*WrappedCommandEvent)) func(*commands.Event) {
  75. return func(ce *commands.Event) {
  76. user := ce.User.(*User)
  77. var portal *Portal
  78. if ce.Portal != nil {
  79. portal = ce.Portal.(*Portal)
  80. }
  81. br := ce.Bridge.Child.(*WABridge)
  82. handler(&WrappedCommandEvent{ce, br, user, portal})
  83. }
  84. }
  85. var (
  86. HelpSectionConnectionManagement = commands.HelpSection{Name: "Connection management", Order: 11}
  87. HelpSectionCreatingPortals = commands.HelpSection{Name: "Creating portals", Order: 15}
  88. HelpSectionPortalManagement = commands.HelpSection{Name: "Portal management", Order: 20}
  89. HelpSectionInvites = commands.HelpSection{Name: "Group invites", Order: 25}
  90. HelpSectionMiscellaneous = commands.HelpSection{Name: "Miscellaneous", Order: 30}
  91. )
  92. var cmdSetRelay = &commands.FullHandler{
  93. Func: wrapCommand(fnSetRelay),
  94. Name: "set-relay",
  95. Help: commands.HelpMeta{
  96. Section: HelpSectionPortalManagement,
  97. Description: "Relay messages in this room through your WhatsApp account.",
  98. },
  99. RequiresPortal: true,
  100. RequiresLogin: true,
  101. }
  102. func fnSetRelay(ce *WrappedCommandEvent) {
  103. if !ce.Bridge.Config.Bridge.Relay.Enabled {
  104. ce.Reply("Relay mode is not enabled on this instance of the bridge")
  105. } else if ce.Bridge.Config.Bridge.Relay.AdminOnly && !ce.User.Admin {
  106. ce.Reply("Only admins are allowed to enable relay mode on this instance of the bridge")
  107. } else {
  108. ce.Portal.RelayUserID = ce.User.MXID
  109. ce.Portal.Update(nil)
  110. ce.Reply("Messages from non-logged-in users in this room will now be bridged through your WhatsApp account")
  111. }
  112. }
  113. var cmdUnsetRelay = &commands.FullHandler{
  114. Func: wrapCommand(fnUnsetRelay),
  115. Name: "unset-relay",
  116. Help: commands.HelpMeta{
  117. Section: HelpSectionPortalManagement,
  118. Description: "Stop relaying messages in this room.",
  119. },
  120. RequiresPortal: true,
  121. }
  122. func fnUnsetRelay(ce *WrappedCommandEvent) {
  123. if !ce.Bridge.Config.Bridge.Relay.Enabled {
  124. ce.Reply("Relay mode is not enabled on this instance of the bridge")
  125. } else if ce.Bridge.Config.Bridge.Relay.AdminOnly && !ce.User.Admin {
  126. ce.Reply("Only admins are allowed to enable relay mode on this instance of the bridge")
  127. } else {
  128. ce.Portal.RelayUserID = ""
  129. ce.Portal.Update(nil)
  130. ce.Reply("Messages from non-logged-in users will no longer be bridged in this room")
  131. }
  132. }
  133. var cmdInviteLink = &commands.FullHandler{
  134. Func: wrapCommand(fnInviteLink),
  135. Name: "invite-link",
  136. Help: commands.HelpMeta{
  137. Section: HelpSectionInvites,
  138. Description: "Get an invite link to the current group chat, optionally regenerating the link and revoking the old link.",
  139. Args: "[--reset]",
  140. },
  141. RequiresPortal: true,
  142. RequiresLogin: true,
  143. }
  144. func fnInviteLink(ce *WrappedCommandEvent) {
  145. reset := len(ce.Args) > 0 && strings.ToLower(ce.Args[0]) == "--reset"
  146. if ce.Portal.IsPrivateChat() {
  147. ce.Reply("Can't get invite link to private chat")
  148. } else if ce.Portal.IsBroadcastList() {
  149. ce.Reply("Can't get invite link to broadcast list")
  150. } else if link, err := ce.User.Client.GetGroupInviteLink(ce.Portal.Key.JID, reset); err != nil {
  151. ce.Reply("Failed to get invite link: %v", err)
  152. } else {
  153. ce.Reply(link)
  154. }
  155. }
  156. var cmdResolveLink = &commands.FullHandler{
  157. Func: wrapCommand(fnResolveLink),
  158. Name: "resolve-link",
  159. Help: commands.HelpMeta{
  160. Section: HelpSectionInvites,
  161. Description: "Resolve a WhatsApp group invite or business message link.",
  162. Args: "<_group, contact, or message link_>",
  163. },
  164. RequiresLogin: true,
  165. }
  166. func fnResolveLink(ce *WrappedCommandEvent) {
  167. if len(ce.Args) == 0 {
  168. ce.Reply("**Usage:** `resolve-link <group or message link>`")
  169. return
  170. }
  171. if strings.HasPrefix(ce.Args[0], whatsmeow.InviteLinkPrefix) {
  172. group, err := ce.User.Client.GetGroupInfoFromLink(ce.Args[0])
  173. if err != nil {
  174. ce.Reply("Failed to get group info: %v", err)
  175. return
  176. }
  177. ce.Reply("That invite link points at %s (`%s`)", group.Name, group.JID)
  178. } else if strings.HasPrefix(ce.Args[0], whatsmeow.BusinessMessageLinkPrefix) || strings.HasPrefix(ce.Args[0], whatsmeow.BusinessMessageLinkDirectPrefix) {
  179. target, err := ce.User.Client.ResolveBusinessMessageLink(ce.Args[0])
  180. if err != nil {
  181. ce.Reply("Failed to get business info: %v", err)
  182. return
  183. }
  184. message := ""
  185. if len(target.Message) > 0 {
  186. parts := strings.Split(target.Message, "\n")
  187. for i, part := range parts {
  188. parts[i] = "> " + html.EscapeString(part)
  189. }
  190. message = fmt.Sprintf(" The following prefilled message is attached:\n\n%s", strings.Join(parts, "\n"))
  191. }
  192. ce.Reply("That link points at %s (+%s).%s", target.PushName, target.JID.User, message)
  193. } else if strings.HasPrefix(ce.Args[0], whatsmeow.ContactQRLinkPrefix) || strings.HasPrefix(ce.Args[0], whatsmeow.ContactQRLinkDirectPrefix) {
  194. target, err := ce.User.Client.ResolveContactQRLink(ce.Args[0])
  195. if err != nil {
  196. ce.Reply("Failed to get contact info: %v", err)
  197. return
  198. }
  199. if target.PushName != "" {
  200. ce.Reply("That link points at %s (+%s)", target.PushName, target.JID.User)
  201. } else {
  202. ce.Reply("That link points at +%s", target.JID.User)
  203. }
  204. } else {
  205. ce.Reply("That doesn't look like a group invite link nor a business message link.")
  206. }
  207. }
  208. var cmdJoin = &commands.FullHandler{
  209. Func: wrapCommand(fnJoin),
  210. Name: "join",
  211. Help: commands.HelpMeta{
  212. Section: HelpSectionInvites,
  213. Description: "Join a group chat with an invite link.",
  214. Args: "<_invite link_>",
  215. },
  216. RequiresLogin: true,
  217. }
  218. func fnJoin(ce *WrappedCommandEvent) {
  219. if len(ce.Args) == 0 {
  220. ce.Reply("**Usage:** `join <invite link>`")
  221. return
  222. } else if !strings.HasPrefix(ce.Args[0], whatsmeow.InviteLinkPrefix) {
  223. ce.Reply("That doesn't look like a WhatsApp invite link")
  224. return
  225. }
  226. jid, err := ce.User.Client.JoinGroupWithLink(ce.Args[0])
  227. if err != nil {
  228. ce.Reply("Failed to join group: %v", err)
  229. return
  230. }
  231. ce.Log.Debugln("%s successfully joined group %s", ce.User.MXID, jid)
  232. ce.Reply("Successfully joined group `%s`, the portal should be created momentarily", jid)
  233. }
  234. func tryDecryptEvent(crypto bridge.Crypto, evt *event.Event) (json.RawMessage, error) {
  235. var data json.RawMessage
  236. if evt.Type != event.EventEncrypted {
  237. data = evt.Content.VeryRaw
  238. } else {
  239. err := evt.Content.ParseRaw(evt.Type)
  240. if err != nil && !errors.Is(err, event.ErrContentAlreadyParsed) {
  241. return nil, err
  242. }
  243. decrypted, err := crypto.Decrypt(evt)
  244. if err != nil {
  245. return nil, err
  246. }
  247. data = decrypted.Content.VeryRaw
  248. }
  249. return data, nil
  250. }
  251. func parseInviteMeta(data json.RawMessage) (*InviteMeta, error) {
  252. result := gjson.GetBytes(data, escapedInviteMetaField)
  253. if !result.Exists() || !result.IsObject() {
  254. return nil, nil
  255. }
  256. var meta InviteMeta
  257. err := json.Unmarshal([]byte(result.Raw), &meta)
  258. if err != nil {
  259. return nil, nil
  260. }
  261. return &meta, nil
  262. }
  263. var cmdAccept = &commands.FullHandler{
  264. Func: wrapCommand(fnAccept),
  265. Name: "accept",
  266. Help: commands.HelpMeta{
  267. Section: HelpSectionInvites,
  268. Description: "Accept a group invite. This can only be used in reply to a group invite message.",
  269. },
  270. RequiresLogin: true,
  271. RequiresPortal: true,
  272. }
  273. func fnAccept(ce *WrappedCommandEvent) {
  274. if len(ce.ReplyTo) == 0 {
  275. ce.Reply("You must reply to a group invite message when using this command.")
  276. } else if evt, err := ce.Portal.MainIntent().GetEvent(ce.RoomID, ce.ReplyTo); err != nil {
  277. ce.Log.Errorln("Failed to get event %s to handle !wa accept command: %v", ce.ReplyTo, err)
  278. ce.Reply("Failed to get reply event")
  279. } else if rawContent, err := tryDecryptEvent(ce.Bridge.Crypto, evt); err != nil {
  280. ce.Log.Errorln("Failed to decrypt event %s to handle !wa accept command: %v", ce.ReplyTo, err)
  281. ce.Reply("Failed to decrypt reply event")
  282. } else if meta, err := parseInviteMeta(rawContent); err != nil || meta == nil {
  283. ce.Reply("That doesn't look like a group invite message.")
  284. } else if meta.Inviter.User == ce.User.JID.User {
  285. ce.Reply("You can't accept your own invites")
  286. } else if err = ce.User.Client.JoinGroupWithInvite(meta.JID, meta.Inviter, meta.Code, meta.Expiration); err != nil {
  287. ce.Reply("Failed to accept group invite: %v", err)
  288. } else {
  289. ce.Reply("Successfully accepted the invite, the portal should be created momentarily")
  290. }
  291. }
  292. var cmdCreate = &commands.FullHandler{
  293. Func: wrapCommand(fnCreate),
  294. Name: "create",
  295. Help: commands.HelpMeta{
  296. Section: HelpSectionCreatingPortals,
  297. Description: "Create a WhatsApp group chat for the current Matrix room.",
  298. },
  299. RequiresLogin: true,
  300. }
  301. func fnCreate(ce *WrappedCommandEvent) {
  302. if ce.Portal != nil {
  303. ce.Reply("This is already a portal room")
  304. return
  305. }
  306. members, err := ce.Bot.JoinedMembers(ce.RoomID)
  307. if err != nil {
  308. ce.Reply("Failed to get room members: %v", err)
  309. return
  310. }
  311. var roomNameEvent event.RoomNameEventContent
  312. err = ce.Bot.StateEvent(ce.RoomID, event.StateRoomName, "", &roomNameEvent)
  313. if err != nil && !errors.Is(err, mautrix.MNotFound) {
  314. ce.Log.Errorln("Failed to get room name to create group:", err)
  315. ce.Reply("Failed to get room name")
  316. return
  317. } else if len(roomNameEvent.Name) == 0 {
  318. ce.Reply("Please set a name for the room first")
  319. return
  320. }
  321. var encryptionEvent event.EncryptionEventContent
  322. err = ce.Bot.StateEvent(ce.RoomID, event.StateEncryption, "", &encryptionEvent)
  323. if err != nil && !errors.Is(err, mautrix.MNotFound) {
  324. ce.Reply("Failed to get room encryption status")
  325. return
  326. }
  327. var createEvent event.CreateEventContent
  328. err = ce.Bot.StateEvent(ce.RoomID, event.StateCreate, "", &createEvent)
  329. if err != nil && !errors.Is(err, mautrix.MNotFound) {
  330. ce.Reply("Failed to get room create event")
  331. return
  332. }
  333. var participants []types.JID
  334. participantDedup := make(map[types.JID]bool)
  335. participantDedup[ce.User.JID.ToNonAD()] = true
  336. participantDedup[types.EmptyJID] = true
  337. for userID := range members.Joined {
  338. jid, ok := ce.Bridge.ParsePuppetMXID(userID)
  339. if !ok {
  340. user := ce.Bridge.GetUserByMXID(userID)
  341. if user != nil && !user.JID.IsEmpty() {
  342. jid = user.JID.ToNonAD()
  343. }
  344. }
  345. if !participantDedup[jid] {
  346. participantDedup[jid] = true
  347. participants = append(participants, jid)
  348. }
  349. }
  350. // TODO check m.space.parent to create rooms directly in communities
  351. messageID := ce.User.Client.GenerateMessageID()
  352. ce.Log.Infofln("Creating group for %s with name %s and participants %+v (create key: %s)", ce.RoomID, roomNameEvent.Name, participants, messageID)
  353. ce.User.createKeyDedup = messageID
  354. resp, err := ce.User.Client.CreateGroup(whatsmeow.ReqCreateGroup{
  355. CreateKey: messageID,
  356. Name: roomNameEvent.Name,
  357. Participants: participants,
  358. GroupParent: types.GroupParent{
  359. IsParent: createEvent.Type == event.RoomTypeSpace,
  360. },
  361. })
  362. if err != nil {
  363. ce.Reply("Failed to create group: %v", err)
  364. return
  365. }
  366. portal := ce.User.GetPortalByJID(resp.JID)
  367. portal.roomCreateLock.Lock()
  368. defer portal.roomCreateLock.Unlock()
  369. if len(portal.MXID) != 0 {
  370. portal.log.Warnln("Detected race condition in room creation")
  371. // TODO race condition, clean up the old room
  372. }
  373. portal.MXID = ce.RoomID
  374. portal.Name = roomNameEvent.Name
  375. portal.IsParent = resp.IsParent
  376. portal.Encrypted = encryptionEvent.Algorithm == id.AlgorithmMegolmV1
  377. if !portal.Encrypted && ce.Bridge.Config.Bridge.Encryption.Default {
  378. _, err = portal.MainIntent().SendStateEvent(portal.MXID, event.StateEncryption, "", portal.GetEncryptionEventContent())
  379. if err != nil {
  380. portal.log.Warnln("Failed to enable encryption in room:", err)
  381. if errors.Is(err, mautrix.MForbidden) {
  382. ce.Reply("I don't seem to have permission to enable encryption in this room.")
  383. } else {
  384. ce.Reply("Failed to enable encryption in room: %v", err)
  385. }
  386. }
  387. portal.Encrypted = true
  388. }
  389. portal.Update(nil)
  390. portal.UpdateBridgeInfo()
  391. ce.User.createKeyDedup = ""
  392. ce.Reply("Successfully created WhatsApp group %s", portal.Key.JID)
  393. }
  394. var cmdLogin = &commands.FullHandler{
  395. Func: wrapCommand(fnLogin),
  396. Name: "login",
  397. Help: commands.HelpMeta{
  398. Section: commands.HelpSectionAuth,
  399. Description: "Link the bridge to your WhatsApp account as a web client.",
  400. Args: "[_phone number_]",
  401. },
  402. }
  403. var looksLikeAPhoneRegex = regexp.MustCompile(`^\+[0-9]+$`)
  404. func fnLogin(ce *WrappedCommandEvent) {
  405. if ce.User.Session != nil {
  406. if ce.User.IsConnected() {
  407. ce.Reply("You're already logged in")
  408. } else {
  409. ce.Reply("You're already logged in. Perhaps you wanted to `reconnect`?")
  410. }
  411. return
  412. }
  413. var phoneNumber string
  414. if len(ce.Args) > 0 {
  415. phoneNumber = strings.TrimSpace(strings.Join(ce.Args, " "))
  416. if !looksLikeAPhoneRegex.MatchString(phoneNumber) {
  417. ce.Reply("When specifying a phone number, it must be provided in international format without spaces or other extra characters")
  418. return
  419. }
  420. }
  421. qrChan, err := ce.User.Login(context.Background())
  422. if err != nil {
  423. ce.ZLog.Err(err).Msg("Failed to start login")
  424. ce.Reply("Failed to log in: %v", err)
  425. return
  426. }
  427. if phoneNumber != "" {
  428. pairingCode, err := ce.User.Client.PairPhone(phoneNumber, true, whatsmeow.PairClientChrome, "Chrome (Linux)")
  429. if err != nil {
  430. ce.ZLog.Err(err).Msg("Failed to start phone code login")
  431. ce.Reply("Failed to start phone code login: %v", err)
  432. go ce.User.DeleteConnection()
  433. return
  434. }
  435. ce.Reply("Scan the code below or enter the following code on your phone to log in: **%s**", pairingCode)
  436. }
  437. var qrEventID id.EventID
  438. for item := range qrChan {
  439. switch item.Event {
  440. case whatsmeow.QRChannelSuccess.Event:
  441. jid := ce.User.Client.Store.ID
  442. ce.Reply("Successfully logged in as +%s (device #%d)", jid.User, jid.Device)
  443. case whatsmeow.QRChannelTimeout.Event:
  444. ce.Reply("Login timed out. Please restart the login.")
  445. case whatsmeow.QRChannelErrUnexpectedEvent.Event:
  446. ce.Reply("Failed to log in: unexpected connection event from server")
  447. case whatsmeow.QRChannelClientOutdated.Event:
  448. ce.Reply("Failed to log in: outdated client. The bridge must be updated to continue.")
  449. case whatsmeow.QRChannelScannedWithoutMultidevice.Event:
  450. ce.Reply("Please enable the WhatsApp multidevice beta and scan the QR code again.")
  451. case "error":
  452. ce.Reply("Failed to log in: %v", item.Error)
  453. case "code":
  454. qrEventID = ce.User.sendQR(ce, item.Code, qrEventID)
  455. }
  456. }
  457. if qrEventID != "" {
  458. _, _ = ce.Bot.RedactEvent(ce.RoomID, qrEventID)
  459. }
  460. }
  461. func (user *User) sendQR(ce *WrappedCommandEvent, code string, prevEvent id.EventID) id.EventID {
  462. url, ok := user.uploadQR(ce, code)
  463. if !ok {
  464. return prevEvent
  465. }
  466. content := event.MessageEventContent{
  467. MsgType: event.MsgImage,
  468. Body: code,
  469. URL: url.CUString(),
  470. }
  471. if len(prevEvent) != 0 {
  472. content.SetEdit(prevEvent)
  473. }
  474. resp, err := ce.Bot.SendMessageEvent(ce.RoomID, event.EventMessage, &content)
  475. if err != nil {
  476. user.log.Errorln("Failed to send edited QR code to user:", err)
  477. } else if len(prevEvent) == 0 {
  478. prevEvent = resp.EventID
  479. }
  480. return prevEvent
  481. }
  482. func (user *User) uploadQR(ce *WrappedCommandEvent, code string) (id.ContentURI, bool) {
  483. qrCode, err := qrcode.Encode(code, qrcode.Low, 256)
  484. if err != nil {
  485. user.log.Errorln("Failed to encode QR code:", err)
  486. ce.Reply("Failed to encode QR code: %v", err)
  487. return id.ContentURI{}, false
  488. }
  489. bot := user.bridge.AS.BotClient()
  490. resp, err := bot.UploadBytes(qrCode, "image/png")
  491. if err != nil {
  492. user.log.Errorln("Failed to upload QR code:", err)
  493. ce.Reply("Failed to upload QR code: %v", err)
  494. return id.ContentURI{}, false
  495. }
  496. return resp.ContentURI, true
  497. }
  498. var cmdLogout = &commands.FullHandler{
  499. Func: wrapCommand(fnLogout),
  500. Name: "logout",
  501. Help: commands.HelpMeta{
  502. Section: commands.HelpSectionAuth,
  503. Description: "Unlink the bridge from your WhatsApp account.",
  504. },
  505. }
  506. func fnLogout(ce *WrappedCommandEvent) {
  507. if ce.User.Session == nil {
  508. ce.Reply("You're not logged in.")
  509. return
  510. } else if !ce.User.IsLoggedIn() {
  511. ce.Reply("You are not connected to WhatsApp. Use the `reconnect` command to reconnect, or `delete-session` to forget all login information.")
  512. return
  513. }
  514. puppet := ce.Bridge.GetPuppetByJID(ce.User.JID)
  515. puppet.ClearCustomMXID()
  516. err := ce.User.Client.Logout()
  517. if err != nil {
  518. ce.User.log.Warnln("Error while logging out:", err)
  519. ce.Reply("Unknown error while logging out: %v", err)
  520. return
  521. }
  522. ce.User.Session = nil
  523. ce.User.removeFromJIDMap(status.BridgeState{StateEvent: status.StateLoggedOut})
  524. ce.User.DeleteConnection()
  525. ce.User.DeleteSession()
  526. ce.Reply("Logged out successfully.")
  527. }
  528. var cmdTogglePresence = &commands.FullHandler{
  529. Func: wrapCommand(fnTogglePresence),
  530. Name: "toggle-presence",
  531. Help: commands.HelpMeta{
  532. Section: HelpSectionConnectionManagement,
  533. Description: "Toggle bridging of presence or read receipts.",
  534. },
  535. }
  536. func fnTogglePresence(ce *WrappedCommandEvent) {
  537. if ce.User.Session == nil {
  538. ce.Reply("You're not logged in.")
  539. return
  540. }
  541. customPuppet := ce.Bridge.GetPuppetByCustomMXID(ce.User.MXID)
  542. if customPuppet == nil {
  543. ce.Reply("You're not logged in with your Matrix account.")
  544. return
  545. }
  546. customPuppet.EnablePresence = !customPuppet.EnablePresence
  547. var newPresence types.Presence
  548. if customPuppet.EnablePresence {
  549. newPresence = types.PresenceAvailable
  550. ce.Reply("Enabled presence bridging")
  551. } else {
  552. newPresence = types.PresenceUnavailable
  553. ce.Reply("Disabled presence bridging")
  554. }
  555. if ce.User.IsLoggedIn() {
  556. err := ce.User.Client.SendPresence(newPresence)
  557. if err != nil {
  558. ce.User.log.Warnln("Failed to set presence:", err)
  559. }
  560. }
  561. customPuppet.Update()
  562. }
  563. var cmdDeleteSession = &commands.FullHandler{
  564. Func: wrapCommand(fnDeleteSession),
  565. Name: "delete-session",
  566. Help: commands.HelpMeta{
  567. Section: commands.HelpSectionAuth,
  568. Description: "Delete session information and disconnect from WhatsApp without sending a logout request.",
  569. },
  570. }
  571. func fnDeleteSession(ce *WrappedCommandEvent) {
  572. if ce.User.Session == nil && ce.User.Client == nil {
  573. ce.Reply("Nothing to purge: no session information stored and no active connection.")
  574. return
  575. }
  576. ce.User.removeFromJIDMap(status.BridgeState{StateEvent: status.StateLoggedOut})
  577. ce.User.DeleteConnection()
  578. ce.User.DeleteSession()
  579. ce.Reply("Session information purged")
  580. }
  581. var cmdReconnect = &commands.FullHandler{
  582. Func: wrapCommand(fnReconnect),
  583. Name: "reconnect",
  584. Help: commands.HelpMeta{
  585. Section: HelpSectionConnectionManagement,
  586. Description: "Reconnect to WhatsApp.",
  587. },
  588. }
  589. func fnReconnect(ce *WrappedCommandEvent) {
  590. if ce.User.Client == nil {
  591. if ce.User.Session == nil {
  592. ce.Reply("You're not logged into WhatsApp. Please log in first.")
  593. } else {
  594. ce.User.Connect()
  595. ce.Reply("Started connecting to WhatsApp")
  596. }
  597. } else {
  598. ce.User.DeleteConnection()
  599. ce.User.BridgeState.Send(status.BridgeState{StateEvent: status.StateTransientDisconnect, Error: WANotConnected})
  600. ce.User.Connect()
  601. ce.Reply("Restarted connection to WhatsApp")
  602. }
  603. }
  604. var cmdDisconnect = &commands.FullHandler{
  605. Func: wrapCommand(fnDisconnect),
  606. Name: "disconnect",
  607. Help: commands.HelpMeta{
  608. Section: HelpSectionConnectionManagement,
  609. Description: "Disconnect from WhatsApp (without logging out).",
  610. },
  611. }
  612. func fnDisconnect(ce *WrappedCommandEvent) {
  613. if ce.User.Client == nil {
  614. ce.Reply("You don't have a WhatsApp connection.")
  615. return
  616. }
  617. ce.User.DeleteConnection()
  618. ce.Reply("Successfully disconnected. Use the `reconnect` command to reconnect.")
  619. ce.User.BridgeState.Send(status.BridgeState{StateEvent: status.StateBadCredentials, Error: WANotConnected})
  620. }
  621. var cmdPing = &commands.FullHandler{
  622. Func: wrapCommand(fnPing),
  623. Name: "ping",
  624. Help: commands.HelpMeta{
  625. Section: HelpSectionConnectionManagement,
  626. Description: "Check your connection to WhatsApp.",
  627. },
  628. }
  629. func fnPing(ce *WrappedCommandEvent) {
  630. if ce.User.Session == nil {
  631. if ce.User.Client != nil {
  632. ce.Reply("Connected to WhatsApp, but not logged in.")
  633. } else {
  634. ce.Reply("You're not logged into WhatsApp.")
  635. }
  636. } else if ce.User.Client == nil || !ce.User.Client.IsConnected() {
  637. ce.Reply("You're logged in as +%s (device #%d), but you don't have a WhatsApp connection.", ce.User.JID.User, ce.User.JID.Device)
  638. } else {
  639. ce.Reply("Logged in as +%s (device #%d), connection to WhatsApp OK (probably)", ce.User.JID.User, ce.User.JID.Device)
  640. if !ce.User.PhoneRecentlySeen(false) {
  641. ce.Reply("Phone hasn't been seen in %s", formatDisconnectTime(time.Now().Sub(ce.User.PhoneLastSeen)))
  642. }
  643. }
  644. }
  645. func canDeletePortal(portal *Portal, userID id.UserID) bool {
  646. if len(portal.MXID) == 0 {
  647. return false
  648. }
  649. members, err := portal.MainIntent().JoinedMembers(portal.MXID)
  650. if err != nil {
  651. portal.log.Errorfln("Failed to get joined members to check if portal can be deleted by %s: %v", userID, err)
  652. return false
  653. }
  654. for otherUser := range members.Joined {
  655. _, isPuppet := portal.bridge.ParsePuppetMXID(otherUser)
  656. if isPuppet || otherUser == portal.bridge.Bot.UserID || otherUser == userID {
  657. continue
  658. }
  659. user := portal.bridge.GetUserByMXID(otherUser)
  660. if user != nil && user.Session != nil {
  661. return false
  662. }
  663. }
  664. return true
  665. }
  666. var cmdDeletePortal = &commands.FullHandler{
  667. Func: wrapCommand(fnDeletePortal),
  668. Name: "delete-portal",
  669. Help: commands.HelpMeta{
  670. Section: HelpSectionPortalManagement,
  671. Description: "Delete the current portal. If the portal is used by other people, this is limited to bridge admins.",
  672. },
  673. RequiresPortal: true,
  674. }
  675. func fnDeletePortal(ce *WrappedCommandEvent) {
  676. if !ce.User.Admin && !canDeletePortal(ce.Portal, ce.User.MXID) {
  677. ce.Reply("Only bridge admins can delete portals with other Matrix users")
  678. return
  679. }
  680. ce.Portal.log.Infoln(ce.User.MXID, "requested deletion of portal.")
  681. ce.Portal.Delete()
  682. ce.Portal.Cleanup(false)
  683. }
  684. var cmdDeleteAllPortals = &commands.FullHandler{
  685. Func: wrapCommand(fnDeleteAllPortals),
  686. Name: "delete-all-portals",
  687. Help: commands.HelpMeta{
  688. Section: HelpSectionPortalManagement,
  689. Description: "Delete all portals.",
  690. },
  691. }
  692. func fnDeleteAllPortals(ce *WrappedCommandEvent) {
  693. portals := ce.Bridge.GetAllPortals()
  694. var portalsToDelete []*Portal
  695. if ce.User.Admin {
  696. portalsToDelete = portals
  697. } else {
  698. portalsToDelete = portals[:0]
  699. for _, portal := range portals {
  700. if canDeletePortal(portal, ce.User.MXID) {
  701. portalsToDelete = append(portalsToDelete, portal)
  702. }
  703. }
  704. }
  705. if len(portalsToDelete) == 0 {
  706. ce.Reply("Didn't find any portals to delete")
  707. return
  708. }
  709. leave := func(portal *Portal) {
  710. if len(portal.MXID) > 0 {
  711. _, _ = portal.MainIntent().KickUser(portal.MXID, &mautrix.ReqKickUser{
  712. Reason: "Deleting portal",
  713. UserID: ce.User.MXID,
  714. })
  715. }
  716. }
  717. customPuppet := ce.Bridge.GetPuppetByCustomMXID(ce.User.MXID)
  718. if customPuppet != nil && customPuppet.CustomIntent() != nil {
  719. intent := customPuppet.CustomIntent()
  720. leave = func(portal *Portal) {
  721. if len(portal.MXID) > 0 {
  722. _, _ = intent.LeaveRoom(portal.MXID)
  723. _, _ = intent.ForgetRoom(portal.MXID)
  724. }
  725. }
  726. }
  727. ce.Reply("Found %d portals, deleting...", len(portalsToDelete))
  728. for _, portal := range portalsToDelete {
  729. portal.Delete()
  730. leave(portal)
  731. }
  732. ce.Reply("Finished deleting portal info. Now cleaning up rooms in background.")
  733. go func() {
  734. for _, portal := range portalsToDelete {
  735. portal.Cleanup(false)
  736. }
  737. ce.Reply("Finished background cleanup of deleted portal rooms.")
  738. }()
  739. }
  740. func matchesQuery(str string, query string) bool {
  741. if query == "" {
  742. return true
  743. }
  744. return strings.Contains(strings.ToLower(str), query)
  745. }
  746. func formatContacts(bridge *WABridge, input map[types.JID]types.ContactInfo, query string) (result []string) {
  747. hasQuery := len(query) > 0
  748. for jid, contact := range input {
  749. if len(contact.FullName) == 0 {
  750. continue
  751. }
  752. puppet := bridge.GetPuppetByJID(jid)
  753. pushName := contact.PushName
  754. if len(pushName) == 0 {
  755. pushName = contact.FullName
  756. }
  757. if !hasQuery || matchesQuery(pushName, query) || matchesQuery(contact.FullName, query) || matchesQuery(jid.User, query) {
  758. result = append(result, fmt.Sprintf("* %s / [%s](https://matrix.to/#/%s) - `+%s`", contact.FullName, pushName, puppet.MXID, jid.User))
  759. }
  760. }
  761. sort.Sort(sort.StringSlice(result))
  762. return
  763. }
  764. func formatGroups(input []*types.GroupInfo, query string) (result []string) {
  765. hasQuery := len(query) > 0
  766. for _, group := range input {
  767. if !hasQuery || matchesQuery(group.GroupName.Name, query) || matchesQuery(group.JID.User, query) {
  768. result = append(result, fmt.Sprintf("* %s - `%s`", group.GroupName.Name, group.JID.User))
  769. }
  770. }
  771. sort.Sort(sort.StringSlice(result))
  772. return
  773. }
  774. var cmdList = &commands.FullHandler{
  775. Func: wrapCommand(fnList),
  776. Name: "list",
  777. Help: commands.HelpMeta{
  778. Section: HelpSectionMiscellaneous,
  779. Description: "Get a list of all contacts and groups.",
  780. Args: "<`contacts`|`groups`> [_page_] [_items per page_]",
  781. },
  782. RequiresLogin: true,
  783. }
  784. func fnList(ce *WrappedCommandEvent) {
  785. if len(ce.Args) == 0 {
  786. ce.Reply("**Usage:** `list <contacts|groups> [page] [items per page]`")
  787. return
  788. }
  789. mode := strings.ToLower(ce.Args[0])
  790. if mode[0] != 'g' && mode[0] != 'c' {
  791. ce.Reply("**Usage:** `list <contacts|groups> [page] [items per page]`")
  792. return
  793. }
  794. var err error
  795. page := 1
  796. max := 100
  797. if len(ce.Args) > 1 {
  798. page, err = strconv.Atoi(ce.Args[1])
  799. if err != nil || page <= 0 {
  800. ce.Reply("\"%s\" isn't a valid page number", ce.Args[1])
  801. return
  802. }
  803. }
  804. if len(ce.Args) > 2 {
  805. max, err = strconv.Atoi(ce.Args[2])
  806. if err != nil || max <= 0 {
  807. ce.Reply("\"%s\" isn't a valid number of items per page", ce.Args[2])
  808. return
  809. } else if max > 400 {
  810. ce.Reply("Warning: a high number of items per page may fail to send a reply")
  811. }
  812. }
  813. contacts := mode[0] == 'c'
  814. typeName := "Groups"
  815. var result []string
  816. if contacts {
  817. typeName = "Contacts"
  818. contactList, err := ce.User.Client.Store.Contacts.GetAllContacts()
  819. if err != nil {
  820. ce.Reply("Failed to get contacts: %s", err)
  821. return
  822. }
  823. result = formatContacts(ce.User.bridge, contactList, "")
  824. } else {
  825. groupList, err := ce.User.Client.GetJoinedGroups()
  826. if err != nil {
  827. ce.Reply("Failed to get groups: %s", err)
  828. return
  829. }
  830. result = formatGroups(groupList, "")
  831. }
  832. if len(result) == 0 {
  833. ce.Reply("No %s found", strings.ToLower(typeName))
  834. return
  835. }
  836. pages := int(math.Ceil(float64(len(result)) / float64(max)))
  837. if (page-1)*max >= len(result) {
  838. if pages == 1 {
  839. ce.Reply("There is only 1 page of %s", strings.ToLower(typeName))
  840. } else {
  841. ce.Reply("There are %d pages of %s", pages, strings.ToLower(typeName))
  842. }
  843. return
  844. }
  845. lastIndex := page * max
  846. if lastIndex > len(result) {
  847. lastIndex = len(result)
  848. }
  849. result = result[(page-1)*max : lastIndex]
  850. ce.Reply("### %s (page %d of %d)\n\n%s", typeName, page, pages, strings.Join(result, "\n"))
  851. }
  852. var cmdSearch = &commands.FullHandler{
  853. Func: wrapCommand(fnSearch),
  854. Name: "search",
  855. Help: commands.HelpMeta{
  856. Section: HelpSectionMiscellaneous,
  857. Description: "Search for contacts or groups.",
  858. Args: "<_query_>",
  859. },
  860. RequiresLogin: true,
  861. }
  862. func fnSearch(ce *WrappedCommandEvent) {
  863. if len(ce.Args) == 0 {
  864. ce.Reply("**Usage:** `search <query>`")
  865. return
  866. }
  867. contactList, err := ce.User.Client.Store.Contacts.GetAllContacts()
  868. if err != nil {
  869. ce.Reply("Failed to get contacts: %s", err)
  870. return
  871. }
  872. groupList, err := ce.User.Client.GetJoinedGroups()
  873. if err != nil {
  874. ce.Reply("Failed to get groups: %s", err)
  875. return
  876. }
  877. query := strings.ToLower(strings.TrimSpace(strings.Join(ce.Args, " ")))
  878. formattedContacts := strings.Join(formatContacts(ce.User.bridge, contactList, query), "\n")
  879. formattedGroups := strings.Join(formatGroups(groupList, query), "\n")
  880. result := make([]string, 0, 2)
  881. if len(formattedContacts) > 0 {
  882. result = append(result, "### Contacts\n\n"+formattedContacts)
  883. }
  884. if len(formattedGroups) > 0 {
  885. result = append(result, "### Groups\n\n"+formattedGroups)
  886. }
  887. if len(result) == 0 {
  888. ce.Reply("No contacts or groups found")
  889. return
  890. }
  891. ce.Reply(strings.Join(result, "\n\n"))
  892. }
  893. var cmdOpen = &commands.FullHandler{
  894. Func: wrapCommand(fnOpen),
  895. Name: "open",
  896. Help: commands.HelpMeta{
  897. Section: HelpSectionCreatingPortals,
  898. Description: "Open a group chat portal.",
  899. Args: "<_group JID_>",
  900. },
  901. RequiresLogin: true,
  902. }
  903. func fnOpen(ce *WrappedCommandEvent) {
  904. if len(ce.Args) == 0 {
  905. ce.Reply("**Usage:** `open <group JID>`")
  906. return
  907. }
  908. var jid types.JID
  909. if strings.ContainsRune(ce.Args[0], '@') {
  910. jid, _ = types.ParseJID(ce.Args[0])
  911. } else {
  912. jid = types.NewJID(ce.Args[0], types.GroupServer)
  913. }
  914. if jid.Server != types.GroupServer || (!strings.ContainsRune(jid.User, '-') && len(jid.User) < 15) {
  915. ce.Reply("That does not look like a group JID")
  916. return
  917. }
  918. info, err := ce.User.Client.GetGroupInfo(jid)
  919. if err != nil {
  920. ce.Reply("Failed to get group info: %v", err)
  921. return
  922. }
  923. ce.Log.Debugln("Importing", jid, "for", ce.User.MXID)
  924. portal := ce.User.GetPortalByJID(info.JID)
  925. if len(portal.MXID) > 0 {
  926. portal.UpdateMatrixRoom(ce.User, info)
  927. ce.Reply("Portal room synced.")
  928. } else {
  929. err = portal.CreateMatrixRoom(ce.User, info, true, true)
  930. if err != nil {
  931. ce.Reply("Failed to create room: %v", err)
  932. } else {
  933. ce.Reply("Portal room created.")
  934. }
  935. }
  936. }
  937. var cmdPM = &commands.FullHandler{
  938. Func: wrapCommand(fnPM),
  939. Name: "pm",
  940. Help: commands.HelpMeta{
  941. Section: HelpSectionCreatingPortals,
  942. Description: "Open a private chat with the given phone number.",
  943. Args: "<_international phone number_>",
  944. },
  945. RequiresLogin: true,
  946. }
  947. func fnPM(ce *WrappedCommandEvent) {
  948. if len(ce.Args) == 0 {
  949. ce.Reply("**Usage:** `pm <international phone number>`")
  950. return
  951. }
  952. user := ce.User
  953. number := strings.Join(ce.Args, "")
  954. resp, err := ce.User.Client.IsOnWhatsApp([]string{number})
  955. if err != nil {
  956. ce.Reply("Failed to check if user is on WhatsApp: %v", err)
  957. return
  958. } else if len(resp) == 0 {
  959. ce.Reply("Didn't get a response to checking if the user is on WhatsApp")
  960. return
  961. }
  962. targetUser := resp[0]
  963. if !targetUser.IsIn {
  964. ce.Reply("The server said +%s is not on WhatsApp", targetUser.JID.User)
  965. return
  966. }
  967. portal, puppet, justCreated, err := user.StartPM(targetUser.JID, "manual PM command")
  968. if err != nil {
  969. ce.Reply("Failed to create portal room: %v", err)
  970. } else if !justCreated {
  971. ce.Reply("You already have a private chat portal with +%s at [%s](https://matrix.to/#/%s)", puppet.JID.User, puppet.Displayname, portal.MXID)
  972. } else {
  973. ce.Reply("Created portal room with +%s and invited you to it.", puppet.JID.User)
  974. }
  975. }
  976. var cmdSync = &commands.FullHandler{
  977. Func: wrapCommand(fnSync),
  978. Name: "sync",
  979. Help: commands.HelpMeta{
  980. Section: HelpSectionMiscellaneous,
  981. Description: "Synchronize data from WhatsApp.",
  982. Args: "<appstate/contacts/groups/space> [--contact-avatars] [--create-portals]",
  983. },
  984. RequiresLogin: true,
  985. }
  986. func fnSync(ce *WrappedCommandEvent) {
  987. args := strings.ToLower(strings.Join(ce.Args, " "))
  988. contacts := strings.Contains(args, "contacts")
  989. appState := strings.Contains(args, "appstate")
  990. space := strings.Contains(args, "space")
  991. groups := strings.Contains(args, "groups") || space
  992. if !contacts && !appState && !space && !groups {
  993. ce.Reply("**Usage:** `sync <appstate/contacts/groups/space> [--contact-avatars] [--create-portals]`")
  994. return
  995. }
  996. createPortals := strings.Contains(args, "--create-portals")
  997. contactAvatars := strings.Contains(args, "--contact-avatars")
  998. if contactAvatars && (!contacts || appState) {
  999. ce.Reply("`--contact-avatars` can only be used with `sync contacts`")
  1000. return
  1001. }
  1002. if createPortals && !groups {
  1003. ce.Reply("`--create-portals` can only be used with `sync groups`")
  1004. return
  1005. }
  1006. if appState {
  1007. for _, name := range appstate.AllPatchNames {
  1008. err := ce.User.Client.FetchAppState(name, true, false)
  1009. if errors.Is(err, appstate.ErrKeyNotFound) {
  1010. ce.Reply("Key not found error syncing app state %s: %v\n\nKey requests are sent automatically, and the sync should happen in the background after your phone responds.", name, err)
  1011. return
  1012. } else if err != nil {
  1013. ce.Reply("Error syncing app state %s: %v", name, err)
  1014. } else if name == appstate.WAPatchCriticalUnblockLow {
  1015. ce.Reply("Synced app state %s, contact sync running in background", name)
  1016. } else {
  1017. ce.Reply("Synced app state %s", name)
  1018. }
  1019. }
  1020. } else if contacts {
  1021. err := ce.User.ResyncContacts(contactAvatars)
  1022. if err != nil {
  1023. ce.Reply("Error resyncing contacts: %v", err)
  1024. } else {
  1025. ce.Reply("Resynced contacts")
  1026. }
  1027. }
  1028. if space {
  1029. if !ce.Bridge.Config.Bridge.PersonalFilteringSpaces {
  1030. ce.Reply("Personal filtering spaces are not enabled on this instance of the bridge")
  1031. return
  1032. }
  1033. keys := ce.Bridge.DB.Portal.FindPrivateChatsNotInSpace(ce.User.JID)
  1034. count := 0
  1035. for _, key := range keys {
  1036. portal := ce.Bridge.GetPortalByJID(key)
  1037. portal.addToPersonalSpace(ce.User)
  1038. count++
  1039. }
  1040. plural := "s"
  1041. if count == 1 {
  1042. plural = ""
  1043. }
  1044. ce.Reply("Added %d DM room%s to space", count, plural)
  1045. }
  1046. if groups {
  1047. err := ce.User.ResyncGroups(createPortals)
  1048. if err != nil {
  1049. ce.Reply("Error resyncing groups: %v", err)
  1050. } else {
  1051. ce.Reply("Resynced groups")
  1052. }
  1053. }
  1054. }
  1055. var cmdDisappearingTimer = &commands.FullHandler{
  1056. Func: wrapCommand(fnDisappearingTimer),
  1057. Name: "disappearing-timer",
  1058. Aliases: []string{"disappear-timer"},
  1059. Help: commands.HelpMeta{
  1060. Section: HelpSectionPortalManagement,
  1061. Description: "Set future messages in the room to disappear after the given time.",
  1062. Args: "<off/1d/7d/90d>",
  1063. },
  1064. RequiresLogin: true,
  1065. RequiresPortal: true,
  1066. }
  1067. func fnDisappearingTimer(ce *WrappedCommandEvent) {
  1068. if len(ce.Args) == 0 {
  1069. ce.Reply("**Usage:** `disappearing-timer <off/1d/7d/90d>`")
  1070. return
  1071. }
  1072. duration, ok := whatsmeow.ParseDisappearingTimerString(ce.Args[0])
  1073. if !ok {
  1074. ce.Reply("Invalid timer '%s'", ce.Args[0])
  1075. return
  1076. }
  1077. prevExpirationTime := ce.Portal.ExpirationTime
  1078. ce.Portal.ExpirationTime = uint32(duration.Seconds())
  1079. err := ce.User.Client.SetDisappearingTimer(ce.Portal.Key.JID, duration)
  1080. if err != nil {
  1081. ce.Reply("Failed to set disappearing timer: %v", err)
  1082. ce.Portal.ExpirationTime = prevExpirationTime
  1083. return
  1084. }
  1085. ce.Portal.Update(nil)
  1086. ce.React("✅")
  1087. }