commands.go 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185
  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. "The phone number parameter is optional: if provided, the bridge will create a 8-character login code " +
  401. "that can be used instead of the QR code.",
  402. Args: "[_phone number_]",
  403. },
  404. }
  405. var looksLikeAPhoneRegex = regexp.MustCompile(`^\+[0-9]+$`)
  406. func fnLogin(ce *WrappedCommandEvent) {
  407. if ce.User.Session != nil {
  408. if ce.User.IsConnected() {
  409. ce.Reply("You're already logged in")
  410. } else {
  411. ce.Reply("You're already logged in. Perhaps you wanted to `reconnect`?")
  412. }
  413. return
  414. }
  415. var phoneNumber string
  416. if len(ce.Args) > 0 {
  417. phoneNumber = strings.TrimSpace(strings.Join(ce.Args, " "))
  418. if !looksLikeAPhoneRegex.MatchString(phoneNumber) {
  419. ce.Reply("When specifying a phone number, it must be provided in international format without spaces or other extra characters")
  420. return
  421. }
  422. }
  423. qrChan, err := ce.User.Login(context.Background())
  424. if err != nil {
  425. ce.ZLog.Err(err).Msg("Failed to start login")
  426. ce.Reply("Failed to log in: %v", err)
  427. return
  428. }
  429. if phoneNumber != "" {
  430. pairingCode, err := ce.User.Client.PairPhone(phoneNumber, true, whatsmeow.PairClientChrome, "Chrome (Linux)")
  431. if err != nil {
  432. ce.ZLog.Err(err).Msg("Failed to start phone code login")
  433. ce.Reply("Failed to start phone code login: %v", err)
  434. go ce.User.DeleteConnection()
  435. return
  436. }
  437. ce.Reply("Scan the code below or enter the following code on your phone to log in: **%s**", pairingCode)
  438. }
  439. var qrEventID id.EventID
  440. for item := range qrChan {
  441. switch item.Event {
  442. case whatsmeow.QRChannelSuccess.Event:
  443. jid := ce.User.Client.Store.ID
  444. ce.Reply("Successfully logged in as +%s (device #%d)", jid.User, jid.Device)
  445. case whatsmeow.QRChannelTimeout.Event:
  446. ce.Reply("Login timed out. Please restart the login.")
  447. case whatsmeow.QRChannelErrUnexpectedEvent.Event:
  448. ce.Reply("Failed to log in: unexpected connection event from server")
  449. case whatsmeow.QRChannelClientOutdated.Event:
  450. ce.Reply("Failed to log in: outdated client. The bridge must be updated to continue.")
  451. case whatsmeow.QRChannelScannedWithoutMultidevice.Event:
  452. ce.Reply("Please enable the WhatsApp multidevice beta and scan the QR code again.")
  453. case "error":
  454. ce.Reply("Failed to log in: %v", item.Error)
  455. case "code":
  456. qrEventID = ce.User.sendQR(ce, item.Code, qrEventID)
  457. }
  458. }
  459. if qrEventID != "" {
  460. _, _ = ce.Bot.RedactEvent(ce.RoomID, qrEventID)
  461. }
  462. }
  463. func (user *User) sendQR(ce *WrappedCommandEvent, code string, prevEvent id.EventID) id.EventID {
  464. url, ok := user.uploadQR(ce, code)
  465. if !ok {
  466. return prevEvent
  467. }
  468. content := event.MessageEventContent{
  469. MsgType: event.MsgImage,
  470. Body: code,
  471. URL: url.CUString(),
  472. }
  473. if len(prevEvent) != 0 {
  474. content.SetEdit(prevEvent)
  475. }
  476. resp, err := ce.Bot.SendMessageEvent(ce.RoomID, event.EventMessage, &content)
  477. if err != nil {
  478. user.log.Errorln("Failed to send edited QR code to user:", err)
  479. } else if len(prevEvent) == 0 {
  480. prevEvent = resp.EventID
  481. }
  482. return prevEvent
  483. }
  484. func (user *User) uploadQR(ce *WrappedCommandEvent, code string) (id.ContentURI, bool) {
  485. qrCode, err := qrcode.Encode(code, qrcode.Low, 256)
  486. if err != nil {
  487. user.log.Errorln("Failed to encode QR code:", err)
  488. ce.Reply("Failed to encode QR code: %v", err)
  489. return id.ContentURI{}, false
  490. }
  491. bot := user.bridge.AS.BotClient()
  492. resp, err := bot.UploadBytes(qrCode, "image/png")
  493. if err != nil {
  494. user.log.Errorln("Failed to upload QR code:", err)
  495. ce.Reply("Failed to upload QR code: %v", err)
  496. return id.ContentURI{}, false
  497. }
  498. return resp.ContentURI, true
  499. }
  500. var cmdLogout = &commands.FullHandler{
  501. Func: wrapCommand(fnLogout),
  502. Name: "logout",
  503. Help: commands.HelpMeta{
  504. Section: commands.HelpSectionAuth,
  505. Description: "Unlink the bridge from your WhatsApp account.",
  506. },
  507. }
  508. func fnLogout(ce *WrappedCommandEvent) {
  509. if ce.User.Session == nil {
  510. ce.Reply("You're not logged in.")
  511. return
  512. } else if !ce.User.IsLoggedIn() {
  513. ce.Reply("You are not connected to WhatsApp. Use the `reconnect` command to reconnect, or `delete-session` to forget all login information.")
  514. return
  515. }
  516. puppet := ce.Bridge.GetPuppetByJID(ce.User.JID)
  517. puppet.ClearCustomMXID()
  518. err := ce.User.Client.Logout()
  519. if err != nil {
  520. ce.User.log.Warnln("Error while logging out:", err)
  521. ce.Reply("Unknown error while logging out: %v", err)
  522. return
  523. }
  524. ce.User.Session = nil
  525. ce.User.removeFromJIDMap(status.BridgeState{StateEvent: status.StateLoggedOut})
  526. ce.User.DeleteConnection()
  527. ce.User.DeleteSession()
  528. ce.Reply("Logged out successfully.")
  529. }
  530. var cmdTogglePresence = &commands.FullHandler{
  531. Func: wrapCommand(fnTogglePresence),
  532. Name: "toggle-presence",
  533. Help: commands.HelpMeta{
  534. Section: HelpSectionConnectionManagement,
  535. Description: "Toggle bridging of presence or read receipts.",
  536. },
  537. }
  538. func fnTogglePresence(ce *WrappedCommandEvent) {
  539. if ce.User.Session == nil {
  540. ce.Reply("You're not logged in.")
  541. return
  542. }
  543. customPuppet := ce.Bridge.GetPuppetByCustomMXID(ce.User.MXID)
  544. if customPuppet == nil {
  545. ce.Reply("You're not logged in with your Matrix account.")
  546. return
  547. }
  548. customPuppet.EnablePresence = !customPuppet.EnablePresence
  549. var newPresence types.Presence
  550. if customPuppet.EnablePresence {
  551. newPresence = types.PresenceAvailable
  552. ce.Reply("Enabled presence bridging")
  553. } else {
  554. newPresence = types.PresenceUnavailable
  555. ce.Reply("Disabled presence bridging")
  556. }
  557. if ce.User.IsLoggedIn() {
  558. err := ce.User.Client.SendPresence(newPresence)
  559. if err != nil {
  560. ce.User.log.Warnln("Failed to set presence:", err)
  561. }
  562. }
  563. customPuppet.Update()
  564. }
  565. var cmdDeleteSession = &commands.FullHandler{
  566. Func: wrapCommand(fnDeleteSession),
  567. Name: "delete-session",
  568. Help: commands.HelpMeta{
  569. Section: commands.HelpSectionAuth,
  570. Description: "Delete session information and disconnect from WhatsApp without sending a logout request.",
  571. },
  572. }
  573. func fnDeleteSession(ce *WrappedCommandEvent) {
  574. if ce.User.Session == nil && ce.User.Client == nil {
  575. ce.Reply("Nothing to purge: no session information stored and no active connection.")
  576. return
  577. }
  578. ce.User.removeFromJIDMap(status.BridgeState{StateEvent: status.StateLoggedOut})
  579. ce.User.DeleteConnection()
  580. ce.User.DeleteSession()
  581. ce.Reply("Session information purged")
  582. }
  583. var cmdReconnect = &commands.FullHandler{
  584. Func: wrapCommand(fnReconnect),
  585. Name: "reconnect",
  586. Help: commands.HelpMeta{
  587. Section: HelpSectionConnectionManagement,
  588. Description: "Reconnect to WhatsApp.",
  589. },
  590. }
  591. func fnReconnect(ce *WrappedCommandEvent) {
  592. if ce.User.Client == nil {
  593. if ce.User.Session == nil {
  594. ce.Reply("You're not logged into WhatsApp. Please log in first.")
  595. } else {
  596. ce.User.Connect()
  597. ce.Reply("Started connecting to WhatsApp")
  598. }
  599. } else {
  600. ce.User.DeleteConnection()
  601. ce.User.BridgeState.Send(status.BridgeState{StateEvent: status.StateTransientDisconnect, Error: WANotConnected})
  602. ce.User.Connect()
  603. ce.Reply("Restarted connection to WhatsApp")
  604. }
  605. }
  606. var cmdDisconnect = &commands.FullHandler{
  607. Func: wrapCommand(fnDisconnect),
  608. Name: "disconnect",
  609. Help: commands.HelpMeta{
  610. Section: HelpSectionConnectionManagement,
  611. Description: "Disconnect from WhatsApp (without logging out).",
  612. },
  613. }
  614. func fnDisconnect(ce *WrappedCommandEvent) {
  615. if ce.User.Client == nil {
  616. ce.Reply("You don't have a WhatsApp connection.")
  617. return
  618. }
  619. ce.User.DeleteConnection()
  620. ce.Reply("Successfully disconnected. Use the `reconnect` command to reconnect.")
  621. ce.User.BridgeState.Send(status.BridgeState{StateEvent: status.StateBadCredentials, Error: WANotConnected})
  622. }
  623. var cmdPing = &commands.FullHandler{
  624. Func: wrapCommand(fnPing),
  625. Name: "ping",
  626. Help: commands.HelpMeta{
  627. Section: HelpSectionConnectionManagement,
  628. Description: "Check your connection to WhatsApp.",
  629. },
  630. }
  631. func fnPing(ce *WrappedCommandEvent) {
  632. if ce.User.Session == nil {
  633. if ce.User.Client != nil {
  634. ce.Reply("Connected to WhatsApp, but not logged in.")
  635. } else {
  636. ce.Reply("You're not logged into WhatsApp.")
  637. }
  638. } else if ce.User.Client == nil || !ce.User.Client.IsConnected() {
  639. 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)
  640. } else {
  641. ce.Reply("Logged in as +%s (device #%d), connection to WhatsApp OK (probably)", ce.User.JID.User, ce.User.JID.Device)
  642. if !ce.User.PhoneRecentlySeen(false) {
  643. ce.Reply("Phone hasn't been seen in %s", formatDisconnectTime(time.Now().Sub(ce.User.PhoneLastSeen)))
  644. }
  645. }
  646. }
  647. func canDeletePortal(portal *Portal, userID id.UserID) bool {
  648. if len(portal.MXID) == 0 {
  649. return false
  650. }
  651. members, err := portal.MainIntent().JoinedMembers(portal.MXID)
  652. if err != nil {
  653. portal.log.Errorfln("Failed to get joined members to check if portal can be deleted by %s: %v", userID, err)
  654. return false
  655. }
  656. for otherUser := range members.Joined {
  657. _, isPuppet := portal.bridge.ParsePuppetMXID(otherUser)
  658. if isPuppet || otherUser == portal.bridge.Bot.UserID || otherUser == userID {
  659. continue
  660. }
  661. user := portal.bridge.GetUserByMXID(otherUser)
  662. if user != nil && user.Session != nil {
  663. return false
  664. }
  665. }
  666. return true
  667. }
  668. var cmdDeletePortal = &commands.FullHandler{
  669. Func: wrapCommand(fnDeletePortal),
  670. Name: "delete-portal",
  671. Help: commands.HelpMeta{
  672. Section: HelpSectionPortalManagement,
  673. Description: "Delete the current portal. If the portal is used by other people, this is limited to bridge admins.",
  674. },
  675. RequiresPortal: true,
  676. }
  677. func fnDeletePortal(ce *WrappedCommandEvent) {
  678. if !ce.User.Admin && !canDeletePortal(ce.Portal, ce.User.MXID) {
  679. ce.Reply("Only bridge admins can delete portals with other Matrix users")
  680. return
  681. }
  682. ce.Portal.log.Infoln(ce.User.MXID, "requested deletion of portal.")
  683. ce.Portal.Delete()
  684. ce.Portal.Cleanup(false)
  685. }
  686. var cmdDeleteAllPortals = &commands.FullHandler{
  687. Func: wrapCommand(fnDeleteAllPortals),
  688. Name: "delete-all-portals",
  689. Help: commands.HelpMeta{
  690. Section: HelpSectionPortalManagement,
  691. Description: "Delete all portals.",
  692. },
  693. }
  694. func fnDeleteAllPortals(ce *WrappedCommandEvent) {
  695. portals := ce.Bridge.GetAllPortals()
  696. var portalsToDelete []*Portal
  697. if ce.User.Admin {
  698. portalsToDelete = portals
  699. } else {
  700. portalsToDelete = portals[:0]
  701. for _, portal := range portals {
  702. if canDeletePortal(portal, ce.User.MXID) {
  703. portalsToDelete = append(portalsToDelete, portal)
  704. }
  705. }
  706. }
  707. if len(portalsToDelete) == 0 {
  708. ce.Reply("Didn't find any portals to delete")
  709. return
  710. }
  711. leave := func(portal *Portal) {
  712. if len(portal.MXID) > 0 {
  713. _, _ = portal.MainIntent().KickUser(portal.MXID, &mautrix.ReqKickUser{
  714. Reason: "Deleting portal",
  715. UserID: ce.User.MXID,
  716. })
  717. }
  718. }
  719. customPuppet := ce.Bridge.GetPuppetByCustomMXID(ce.User.MXID)
  720. if customPuppet != nil && customPuppet.CustomIntent() != nil {
  721. intent := customPuppet.CustomIntent()
  722. leave = func(portal *Portal) {
  723. if len(portal.MXID) > 0 {
  724. _, _ = intent.LeaveRoom(portal.MXID)
  725. _, _ = intent.ForgetRoom(portal.MXID)
  726. }
  727. }
  728. }
  729. ce.Reply("Found %d portals, deleting...", len(portalsToDelete))
  730. for _, portal := range portalsToDelete {
  731. portal.Delete()
  732. leave(portal)
  733. }
  734. ce.Reply("Finished deleting portal info. Now cleaning up rooms in background.")
  735. go func() {
  736. for _, portal := range portalsToDelete {
  737. portal.Cleanup(false)
  738. }
  739. ce.Reply("Finished background cleanup of deleted portal rooms.")
  740. }()
  741. }
  742. func matchesQuery(str string, query string) bool {
  743. if query == "" {
  744. return true
  745. }
  746. return strings.Contains(strings.ToLower(str), query)
  747. }
  748. func formatContacts(bridge *WABridge, input map[types.JID]types.ContactInfo, query string) (result []string) {
  749. hasQuery := len(query) > 0
  750. for jid, contact := range input {
  751. if len(contact.FullName) == 0 {
  752. continue
  753. }
  754. puppet := bridge.GetPuppetByJID(jid)
  755. pushName := contact.PushName
  756. if len(pushName) == 0 {
  757. pushName = contact.FullName
  758. }
  759. if !hasQuery || matchesQuery(pushName, query) || matchesQuery(contact.FullName, query) || matchesQuery(jid.User, query) {
  760. result = append(result, fmt.Sprintf("* %s / [%s](https://matrix.to/#/%s) - `+%s`", contact.FullName, pushName, puppet.MXID, jid.User))
  761. }
  762. }
  763. sort.Sort(sort.StringSlice(result))
  764. return
  765. }
  766. func formatGroups(input []*types.GroupInfo, query string) (result []string) {
  767. hasQuery := len(query) > 0
  768. for _, group := range input {
  769. if !hasQuery || matchesQuery(group.GroupName.Name, query) || matchesQuery(group.JID.User, query) {
  770. result = append(result, fmt.Sprintf("* %s - `%s`", group.GroupName.Name, group.JID.User))
  771. }
  772. }
  773. sort.Sort(sort.StringSlice(result))
  774. return
  775. }
  776. var cmdList = &commands.FullHandler{
  777. Func: wrapCommand(fnList),
  778. Name: "list",
  779. Help: commands.HelpMeta{
  780. Section: HelpSectionMiscellaneous,
  781. Description: "Get a list of all contacts and groups.",
  782. Args: "<`contacts`|`groups`> [_page_] [_items per page_]",
  783. },
  784. RequiresLogin: true,
  785. }
  786. func fnList(ce *WrappedCommandEvent) {
  787. if len(ce.Args) == 0 {
  788. ce.Reply("**Usage:** `list <contacts|groups> [page] [items per page]`")
  789. return
  790. }
  791. mode := strings.ToLower(ce.Args[0])
  792. if mode[0] != 'g' && mode[0] != 'c' {
  793. ce.Reply("**Usage:** `list <contacts|groups> [page] [items per page]`")
  794. return
  795. }
  796. var err error
  797. page := 1
  798. max := 100
  799. if len(ce.Args) > 1 {
  800. page, err = strconv.Atoi(ce.Args[1])
  801. if err != nil || page <= 0 {
  802. ce.Reply("\"%s\" isn't a valid page number", ce.Args[1])
  803. return
  804. }
  805. }
  806. if len(ce.Args) > 2 {
  807. max, err = strconv.Atoi(ce.Args[2])
  808. if err != nil || max <= 0 {
  809. ce.Reply("\"%s\" isn't a valid number of items per page", ce.Args[2])
  810. return
  811. } else if max > 400 {
  812. ce.Reply("Warning: a high number of items per page may fail to send a reply")
  813. }
  814. }
  815. contacts := mode[0] == 'c'
  816. typeName := "Groups"
  817. var result []string
  818. if contacts {
  819. typeName = "Contacts"
  820. contactList, err := ce.User.Client.Store.Contacts.GetAllContacts()
  821. if err != nil {
  822. ce.Reply("Failed to get contacts: %s", err)
  823. return
  824. }
  825. result = formatContacts(ce.User.bridge, contactList, "")
  826. } else {
  827. groupList, err := ce.User.Client.GetJoinedGroups()
  828. if err != nil {
  829. ce.Reply("Failed to get groups: %s", err)
  830. return
  831. }
  832. result = formatGroups(groupList, "")
  833. }
  834. if len(result) == 0 {
  835. ce.Reply("No %s found", strings.ToLower(typeName))
  836. return
  837. }
  838. pages := int(math.Ceil(float64(len(result)) / float64(max)))
  839. if (page-1)*max >= len(result) {
  840. if pages == 1 {
  841. ce.Reply("There is only 1 page of %s", strings.ToLower(typeName))
  842. } else {
  843. ce.Reply("There are %d pages of %s", pages, strings.ToLower(typeName))
  844. }
  845. return
  846. }
  847. lastIndex := page * max
  848. if lastIndex > len(result) {
  849. lastIndex = len(result)
  850. }
  851. result = result[(page-1)*max : lastIndex]
  852. ce.Reply("### %s (page %d of %d)\n\n%s", typeName, page, pages, strings.Join(result, "\n"))
  853. }
  854. var cmdSearch = &commands.FullHandler{
  855. Func: wrapCommand(fnSearch),
  856. Name: "search",
  857. Help: commands.HelpMeta{
  858. Section: HelpSectionMiscellaneous,
  859. Description: "Search for contacts or groups.",
  860. Args: "<_query_>",
  861. },
  862. RequiresLogin: true,
  863. }
  864. func fnSearch(ce *WrappedCommandEvent) {
  865. if len(ce.Args) == 0 {
  866. ce.Reply("**Usage:** `search <query>`")
  867. return
  868. }
  869. contactList, err := ce.User.Client.Store.Contacts.GetAllContacts()
  870. if err != nil {
  871. ce.Reply("Failed to get contacts: %s", err)
  872. return
  873. }
  874. groupList, err := ce.User.Client.GetJoinedGroups()
  875. if err != nil {
  876. ce.Reply("Failed to get groups: %s", err)
  877. return
  878. }
  879. query := strings.ToLower(strings.TrimSpace(strings.Join(ce.Args, " ")))
  880. formattedContacts := strings.Join(formatContacts(ce.User.bridge, contactList, query), "\n")
  881. formattedGroups := strings.Join(formatGroups(groupList, query), "\n")
  882. result := make([]string, 0, 2)
  883. if len(formattedContacts) > 0 {
  884. result = append(result, "### Contacts\n\n"+formattedContacts)
  885. }
  886. if len(formattedGroups) > 0 {
  887. result = append(result, "### Groups\n\n"+formattedGroups)
  888. }
  889. if len(result) == 0 {
  890. ce.Reply("No contacts or groups found")
  891. return
  892. }
  893. ce.Reply(strings.Join(result, "\n\n"))
  894. }
  895. var cmdOpen = &commands.FullHandler{
  896. Func: wrapCommand(fnOpen),
  897. Name: "open",
  898. Help: commands.HelpMeta{
  899. Section: HelpSectionCreatingPortals,
  900. Description: "Open a group chat portal.",
  901. Args: "<_group JID_>",
  902. },
  903. RequiresLogin: true,
  904. }
  905. func fnOpen(ce *WrappedCommandEvent) {
  906. if len(ce.Args) == 0 {
  907. ce.Reply("**Usage:** `open <group JID>`")
  908. return
  909. }
  910. var jid types.JID
  911. if strings.ContainsRune(ce.Args[0], '@') {
  912. jid, _ = types.ParseJID(ce.Args[0])
  913. } else {
  914. jid = types.NewJID(ce.Args[0], types.GroupServer)
  915. }
  916. if jid.Server != types.GroupServer || (!strings.ContainsRune(jid.User, '-') && len(jid.User) < 15) {
  917. ce.Reply("That does not look like a group JID")
  918. return
  919. }
  920. info, err := ce.User.Client.GetGroupInfo(jid)
  921. if err != nil {
  922. ce.Reply("Failed to get group info: %v", err)
  923. return
  924. }
  925. ce.Log.Debugln("Importing", jid, "for", ce.User.MXID)
  926. portal := ce.User.GetPortalByJID(info.JID)
  927. if len(portal.MXID) > 0 {
  928. portal.UpdateMatrixRoom(ce.User, info)
  929. ce.Reply("Portal room synced.")
  930. } else {
  931. err = portal.CreateMatrixRoom(ce.User, info, true, true)
  932. if err != nil {
  933. ce.Reply("Failed to create room: %v", err)
  934. } else {
  935. ce.Reply("Portal room created.")
  936. }
  937. }
  938. }
  939. var cmdPM = &commands.FullHandler{
  940. Func: wrapCommand(fnPM),
  941. Name: "pm",
  942. Help: commands.HelpMeta{
  943. Section: HelpSectionCreatingPortals,
  944. Description: "Open a private chat with the given phone number.",
  945. Args: "<_international phone number_>",
  946. },
  947. RequiresLogin: true,
  948. }
  949. func fnPM(ce *WrappedCommandEvent) {
  950. if len(ce.Args) == 0 {
  951. ce.Reply("**Usage:** `pm <international phone number>`")
  952. return
  953. }
  954. user := ce.User
  955. number := strings.Join(ce.Args, "")
  956. resp, err := ce.User.Client.IsOnWhatsApp([]string{number})
  957. if err != nil {
  958. ce.Reply("Failed to check if user is on WhatsApp: %v", err)
  959. return
  960. } else if len(resp) == 0 {
  961. ce.Reply("Didn't get a response to checking if the user is on WhatsApp")
  962. return
  963. }
  964. targetUser := resp[0]
  965. if !targetUser.IsIn {
  966. ce.Reply("The server said +%s is not on WhatsApp", targetUser.JID.User)
  967. return
  968. }
  969. portal, puppet, justCreated, err := user.StartPM(targetUser.JID, "manual PM command")
  970. if err != nil {
  971. ce.Reply("Failed to create portal room: %v", err)
  972. } else if !justCreated {
  973. ce.Reply("You already have a private chat portal with +%s at [%s](https://matrix.to/#/%s)", puppet.JID.User, puppet.Displayname, portal.MXID)
  974. } else {
  975. ce.Reply("Created portal room with +%s and invited you to it.", puppet.JID.User)
  976. }
  977. }
  978. var cmdSync = &commands.FullHandler{
  979. Func: wrapCommand(fnSync),
  980. Name: "sync",
  981. Help: commands.HelpMeta{
  982. Section: HelpSectionMiscellaneous,
  983. Description: "Synchronize data from WhatsApp.",
  984. Args: "<appstate/contacts/groups/space> [--contact-avatars] [--create-portals]",
  985. },
  986. RequiresLogin: true,
  987. }
  988. func fnSync(ce *WrappedCommandEvent) {
  989. args := strings.ToLower(strings.Join(ce.Args, " "))
  990. contacts := strings.Contains(args, "contacts")
  991. appState := strings.Contains(args, "appstate")
  992. space := strings.Contains(args, "space")
  993. groups := strings.Contains(args, "groups") || space
  994. if !contacts && !appState && !space && !groups {
  995. ce.Reply("**Usage:** `sync <appstate/contacts/groups/space> [--contact-avatars] [--create-portals]`")
  996. return
  997. }
  998. createPortals := strings.Contains(args, "--create-portals")
  999. contactAvatars := strings.Contains(args, "--contact-avatars")
  1000. if contactAvatars && (!contacts || appState) {
  1001. ce.Reply("`--contact-avatars` can only be used with `sync contacts`")
  1002. return
  1003. }
  1004. if createPortals && !groups {
  1005. ce.Reply("`--create-portals` can only be used with `sync groups`")
  1006. return
  1007. }
  1008. if appState {
  1009. for _, name := range appstate.AllPatchNames {
  1010. err := ce.User.Client.FetchAppState(name, true, false)
  1011. if errors.Is(err, appstate.ErrKeyNotFound) {
  1012. 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)
  1013. return
  1014. } else if err != nil {
  1015. ce.Reply("Error syncing app state %s: %v", name, err)
  1016. } else if name == appstate.WAPatchCriticalUnblockLow {
  1017. ce.Reply("Synced app state %s, contact sync running in background", name)
  1018. } else {
  1019. ce.Reply("Synced app state %s", name)
  1020. }
  1021. }
  1022. } else if contacts {
  1023. err := ce.User.ResyncContacts(contactAvatars)
  1024. if err != nil {
  1025. ce.Reply("Error resyncing contacts: %v", err)
  1026. } else {
  1027. ce.Reply("Resynced contacts")
  1028. }
  1029. }
  1030. if space {
  1031. if !ce.Bridge.Config.Bridge.PersonalFilteringSpaces {
  1032. ce.Reply("Personal filtering spaces are not enabled on this instance of the bridge")
  1033. return
  1034. }
  1035. keys := ce.Bridge.DB.Portal.FindPrivateChatsNotInSpace(ce.User.JID)
  1036. count := 0
  1037. for _, key := range keys {
  1038. portal := ce.Bridge.GetPortalByJID(key)
  1039. portal.addToPersonalSpace(ce.User)
  1040. count++
  1041. }
  1042. plural := "s"
  1043. if count == 1 {
  1044. plural = ""
  1045. }
  1046. ce.Reply("Added %d DM room%s to space", count, plural)
  1047. }
  1048. if groups {
  1049. err := ce.User.ResyncGroups(createPortals)
  1050. if err != nil {
  1051. ce.Reply("Error resyncing groups: %v", err)
  1052. } else {
  1053. ce.Reply("Resynced groups")
  1054. }
  1055. }
  1056. }
  1057. var cmdDisappearingTimer = &commands.FullHandler{
  1058. Func: wrapCommand(fnDisappearingTimer),
  1059. Name: "disappearing-timer",
  1060. Aliases: []string{"disappear-timer"},
  1061. Help: commands.HelpMeta{
  1062. Section: HelpSectionPortalManagement,
  1063. Description: "Set future messages in the room to disappear after the given time.",
  1064. Args: "<off/1d/7d/90d>",
  1065. },
  1066. RequiresLogin: true,
  1067. RequiresPortal: true,
  1068. }
  1069. func fnDisappearingTimer(ce *WrappedCommandEvent) {
  1070. if len(ce.Args) == 0 {
  1071. ce.Reply("**Usage:** `disappearing-timer <off/1d/7d/90d>`")
  1072. return
  1073. }
  1074. duration, ok := whatsmeow.ParseDisappearingTimerString(ce.Args[0])
  1075. if !ok {
  1076. ce.Reply("Invalid timer '%s'", ce.Args[0])
  1077. return
  1078. }
  1079. prevExpirationTime := ce.Portal.ExpirationTime
  1080. ce.Portal.ExpirationTime = uint32(duration.Seconds())
  1081. err := ce.User.Client.SetDisappearingTimer(ce.Portal.Key.JID, duration)
  1082. if err != nil {
  1083. ce.Reply("Failed to set disappearing timer: %v", err)
  1084. ce.Portal.ExpirationTime = prevExpirationTime
  1085. return
  1086. }
  1087. ce.Portal.Update(nil)
  1088. ce.React("✅")
  1089. }