commands.go 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170
  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. "errors"
  20. "fmt"
  21. "html"
  22. "math"
  23. "sort"
  24. "strconv"
  25. "strings"
  26. "github.com/skip2/go-qrcode"
  27. "maunium.net/go/maulogger/v2"
  28. "go.mau.fi/whatsmeow"
  29. "go.mau.fi/whatsmeow/appstate"
  30. "go.mau.fi/whatsmeow/types"
  31. "maunium.net/go/mautrix"
  32. "maunium.net/go/mautrix/appservice"
  33. "maunium.net/go/mautrix/event"
  34. "maunium.net/go/mautrix/format"
  35. "maunium.net/go/mautrix/id"
  36. )
  37. type CommandHandler struct {
  38. bridge *Bridge
  39. log maulogger.Logger
  40. }
  41. // NewCommandHandler creates a CommandHandler
  42. func NewCommandHandler(bridge *Bridge) *CommandHandler {
  43. return &CommandHandler{
  44. bridge: bridge,
  45. log: bridge.Log.Sub("Command handler"),
  46. }
  47. }
  48. // CommandEvent stores all data which might be used to handle commands
  49. type CommandEvent struct {
  50. Bot *appservice.IntentAPI
  51. Bridge *Bridge
  52. Portal *Portal
  53. Handler *CommandHandler
  54. RoomID id.RoomID
  55. EventID id.EventID
  56. User *User
  57. Command string
  58. Args []string
  59. ReplyTo id.EventID
  60. }
  61. // Reply sends a reply to command as notice
  62. func (ce *CommandEvent) Reply(msg string, args ...interface{}) {
  63. content := format.RenderMarkdown(fmt.Sprintf(msg, args...), true, false)
  64. content.MsgType = event.MsgNotice
  65. intent := ce.Bot
  66. if ce.Portal != nil && ce.Portal.IsPrivateChat() {
  67. intent = ce.Portal.MainIntent()
  68. }
  69. _, err := intent.SendMessageEvent(ce.RoomID, event.EventMessage, content)
  70. if err != nil {
  71. ce.Handler.log.Warnfln("Failed to reply to command from %s: %v", ce.User.MXID, err)
  72. }
  73. }
  74. // Handle handles messages to the bridge
  75. func (handler *CommandHandler) Handle(roomID id.RoomID, eventID id.EventID, user *User, message string, replyTo id.EventID) {
  76. args := strings.Fields(message)
  77. if len(args) == 0 {
  78. args = []string{"unknown-command"}
  79. }
  80. ce := &CommandEvent{
  81. Bot: handler.bridge.Bot,
  82. Bridge: handler.bridge,
  83. Portal: handler.bridge.GetPortalByMXID(roomID),
  84. Handler: handler,
  85. RoomID: roomID,
  86. EventID: eventID,
  87. User: user,
  88. Command: strings.ToLower(args[0]),
  89. Args: args[1:],
  90. ReplyTo: replyTo,
  91. }
  92. handler.log.Debugfln("%s sent '%s' in %s", user.MXID, message, roomID)
  93. handler.CommandMux(ce)
  94. }
  95. func (handler *CommandHandler) CommandMux(ce *CommandEvent) {
  96. switch ce.Command {
  97. case "login":
  98. handler.CommandLogin(ce)
  99. case "ping-matrix":
  100. handler.CommandPingMatrix(ce)
  101. case "logout-matrix":
  102. handler.CommandLogoutMatrix(ce)
  103. case "help":
  104. handler.CommandHelp(ce)
  105. case "version":
  106. handler.CommandVersion(ce)
  107. case "reconnect", "connect":
  108. handler.CommandReconnect(ce)
  109. case "disconnect":
  110. handler.CommandDisconnect(ce)
  111. case "ping":
  112. handler.CommandPing(ce)
  113. case "delete-session":
  114. handler.CommandDeleteSession(ce)
  115. case "delete-portal":
  116. handler.CommandDeletePortal(ce)
  117. case "delete-all-portals":
  118. handler.CommandDeleteAllPortals(ce)
  119. case "discard-megolm-session", "discard-session":
  120. handler.CommandDiscardMegolmSession(ce)
  121. case "dev-test":
  122. handler.CommandDevTest(ce)
  123. case "set-pl":
  124. handler.CommandSetPowerLevel(ce)
  125. case "logout":
  126. handler.CommandLogout(ce)
  127. case "toggle":
  128. handler.CommandToggle(ce)
  129. case "set-relay", "unset-relay", "login-matrix", "sync", "list", "search", "open", "pm", "invite-link", "resolve", "resolve-link", "join", "create", "accept":
  130. if !ce.User.HasSession() {
  131. ce.Reply("You are not logged in. Use the `login` command to log into WhatsApp.")
  132. return
  133. } else if !ce.User.IsLoggedIn() {
  134. ce.Reply("You are not connected to WhatsApp. Use the `reconnect` command to reconnect.")
  135. return
  136. }
  137. switch ce.Command {
  138. case "set-relay":
  139. handler.CommandSetRelay(ce)
  140. case "unset-relay":
  141. handler.CommandUnsetRelay(ce)
  142. case "login-matrix":
  143. handler.CommandLoginMatrix(ce)
  144. case "sync":
  145. handler.CommandSync(ce)
  146. case "list":
  147. handler.CommandList(ce)
  148. case "search":
  149. handler.CommandSearch(ce)
  150. case "open":
  151. handler.CommandOpen(ce)
  152. case "pm":
  153. handler.CommandPM(ce)
  154. case "invite-link":
  155. handler.CommandInviteLink(ce)
  156. case "resolve", "resolve-link":
  157. handler.CommandResolveLink(ce)
  158. case "join":
  159. handler.CommandJoin(ce)
  160. case "create":
  161. handler.CommandCreate(ce)
  162. case "accept":
  163. handler.CommandAccept(ce)
  164. }
  165. default:
  166. ce.Reply("Unknown command, use the `help` command for help.")
  167. }
  168. }
  169. func (handler *CommandHandler) CommandDiscardMegolmSession(ce *CommandEvent) {
  170. if handler.bridge.Crypto == nil {
  171. ce.Reply("This bridge instance doesn't have end-to-bridge encryption enabled")
  172. } else if !ce.User.Admin {
  173. ce.Reply("Only the bridge admin can reset Megolm sessions")
  174. } else {
  175. handler.bridge.Crypto.ResetSession(ce.RoomID)
  176. ce.Reply("Successfully reset Megolm session in this room. New decryption keys will be shared the next time a message is sent from WhatsApp.")
  177. }
  178. }
  179. const cmdSetRelayHelp = `set-relay - Relay messages in this room through your WhatsApp account.`
  180. func (handler *CommandHandler) CommandSetRelay(ce *CommandEvent) {
  181. if !handler.bridge.Config.Bridge.Relay.Enabled {
  182. ce.Reply("Relay mode is not enabled on this instance of the bridge")
  183. } else if ce.Portal == nil {
  184. ce.Reply("This is not a portal room")
  185. } else if handler.bridge.Config.Bridge.Relay.AdminOnly && !ce.User.Admin {
  186. ce.Reply("Only admins are allowed to enable relay mode on this instance of the bridge")
  187. } else {
  188. ce.Portal.RelayUserID = ce.User.MXID
  189. ce.Portal.Update()
  190. ce.Reply("Messages from non-logged-in users in this room will now be bridged through your WhatsApp account")
  191. }
  192. }
  193. const cmdUnsetRelayHelp = `unset-relay - Stop relaying messages in this room.`
  194. func (handler *CommandHandler) CommandUnsetRelay(ce *CommandEvent) {
  195. if !handler.bridge.Config.Bridge.Relay.Enabled {
  196. ce.Reply("Relay mode is not enabled on this instance of the bridge")
  197. } else if ce.Portal == nil {
  198. ce.Reply("This is not a portal room")
  199. } else if handler.bridge.Config.Bridge.Relay.AdminOnly && !ce.User.Admin {
  200. ce.Reply("Only admins are allowed to enable relay mode on this instance of the bridge")
  201. } else {
  202. ce.Portal.RelayUserID = ""
  203. ce.Portal.Update()
  204. ce.Reply("Messages from non-logged-in users will no longer be bridged in this room")
  205. }
  206. }
  207. func (handler *CommandHandler) CommandDevTest(_ *CommandEvent) {
  208. }
  209. const cmdVersionHelp = `version - View the bridge version`
  210. func (handler *CommandHandler) CommandVersion(ce *CommandEvent) {
  211. linkifiedVersion := fmt.Sprintf("v%s", Version)
  212. if Tag == Version {
  213. linkifiedVersion = fmt.Sprintf("[v%s](%s/releases/v%s)", Version, URL, Tag)
  214. } else if len(Commit) > 8 {
  215. linkifiedVersion = strings.Replace(linkifiedVersion, Commit[:8], fmt.Sprintf("[%s](%s/commit/%s)", Commit[:8], URL, Commit), 1)
  216. }
  217. ce.Reply(fmt.Sprintf("[%s](%s) %s (%s)", Name, URL, linkifiedVersion, BuildTime))
  218. }
  219. const cmdInviteLinkHelp = `invite-link [--reset] - Get an invite link to the current group chat, optionally regenerating the link and revoking the old link.`
  220. func (handler *CommandHandler) CommandInviteLink(ce *CommandEvent) {
  221. reset := len(ce.Args) > 0 && strings.ToLower(ce.Args[0]) == "--reset"
  222. if ce.Portal == nil {
  223. ce.Reply("Not a portal room")
  224. } else if ce.Portal.IsPrivateChat() {
  225. ce.Reply("Can't get invite link to private chat")
  226. } else if ce.Portal.IsBroadcastList() {
  227. ce.Reply("Can't get invite link to broadcast list")
  228. } else if link, err := ce.User.Client.GetGroupInviteLink(ce.Portal.Key.JID, reset); err != nil {
  229. ce.Reply("Failed to get invite link: %v", err)
  230. } else {
  231. ce.Reply(link)
  232. }
  233. }
  234. const cmdResolveLinkHelp = `resolve-link <group or message link> - Resolve a WhatsApp group invite or business message link.`
  235. func (handler *CommandHandler) CommandResolveLink(ce *CommandEvent) {
  236. if len(ce.Args) == 0 {
  237. ce.Reply("**Usage:** `resolve-link <group or message link>`")
  238. return
  239. }
  240. if strings.HasPrefix(ce.Args[0], whatsmeow.InviteLinkPrefix) {
  241. group, err := ce.User.Client.GetGroupInfoFromLink(ce.Args[0])
  242. if err != nil {
  243. ce.Reply("Failed to get group info: %v", err)
  244. return
  245. }
  246. ce.Reply("That invite link points at %s (`%s`)", group.Name, group.JID)
  247. } else if strings.HasPrefix(ce.Args[0], whatsmeow.BusinessMessageLinkPrefix) || strings.HasPrefix(ce.Args[0], whatsmeow.BusinessMessageLinkDirectPrefix) {
  248. target, err := ce.User.Client.ResolveBusinessMessageLink(ce.Args[0])
  249. if err != nil {
  250. ce.Reply("Failed to get business info: %v", err)
  251. return
  252. }
  253. message := ""
  254. if len(target.Message) > 0 {
  255. parts := strings.Split(target.Message, "\n")
  256. for i, part := range parts {
  257. parts[i] = "> " + html.EscapeString(part)
  258. }
  259. message = fmt.Sprintf(" The following prefilled message is attached:\n\n%s", strings.Join(parts, "\n"))
  260. }
  261. ce.Reply("That link points at %s (+%s).%s", target.PushName, target.JID.User, message)
  262. } else {
  263. ce.Reply("That doesn't look like a group invite link nor a business message link.")
  264. }
  265. }
  266. const cmdJoinHelp = `join <invite link> - Join a group chat with an invite link.`
  267. func (handler *CommandHandler) CommandJoin(ce *CommandEvent) {
  268. if len(ce.Args) == 0 {
  269. ce.Reply("**Usage:** `join <invite link>`")
  270. return
  271. } else if !strings.HasPrefix(ce.Args[0], whatsmeow.InviteLinkPrefix) {
  272. ce.Reply("That doesn't look like a WhatsApp invite link")
  273. return
  274. }
  275. jid, err := ce.User.Client.JoinGroupWithLink(ce.Args[0])
  276. if err != nil {
  277. ce.Reply("Failed to join group: %v", err)
  278. return
  279. }
  280. handler.log.Debugln("%s successfully joined group %s", ce.User.MXID, jid)
  281. ce.Reply("Successfully joined group `%s`, the portal should be created momentarily", jid)
  282. }
  283. func (handler *CommandHandler) CommandAccept(ce *CommandEvent) {
  284. if ce.Portal == nil || len(ce.ReplyTo) == 0 {
  285. ce.Reply("You must reply to a group invite message when using this command.")
  286. } else if evt, err := ce.Portal.MainIntent().GetEvent(ce.RoomID, ce.ReplyTo); err != nil {
  287. handler.log.Errorln("Failed to get event %s to handle !wa accept command: %v", ce.ReplyTo, err)
  288. ce.Reply("Failed to get reply event")
  289. } else if meta, ok := evt.Content.Raw[inviteMetaField].(map[string]interface{}); !ok {
  290. ce.Reply("That doesn't look like a group invite message.")
  291. } else if jid, inviter, code, expiration, ok := parseInviteMeta(meta); !ok {
  292. ce.Reply("That doesn't look like a group invite message.")
  293. } else if inviter.User == ce.User.JID.User {
  294. ce.Reply("You can't accept your own invites")
  295. } else if err = ce.User.Client.JoinGroupWithInvite(jid, inviter, code, expiration); err != nil {
  296. ce.Reply("Failed to accept group invite: %v", err)
  297. } else {
  298. ce.Reply("Successfully accepted the invite, the portal should be created momentarily")
  299. }
  300. }
  301. const cmdCreateHelp = `create - Create a group chat.`
  302. func (handler *CommandHandler) CommandCreate(ce *CommandEvent) {
  303. if ce.Portal != nil {
  304. ce.Reply("This is already a portal room")
  305. return
  306. }
  307. members, err := ce.Bot.JoinedMembers(ce.RoomID)
  308. if err != nil {
  309. ce.Reply("Failed to get room members: %v", err)
  310. return
  311. }
  312. var roomNameEvent event.RoomNameEventContent
  313. err = ce.Bot.StateEvent(ce.RoomID, event.StateRoomName, "", &roomNameEvent)
  314. if err != nil && !errors.Is(err, mautrix.MNotFound) {
  315. handler.log.Errorln("Failed to get room name to create group:", err)
  316. ce.Reply("Failed to get room name")
  317. return
  318. } else if len(roomNameEvent.Name) == 0 {
  319. ce.Reply("Please set a name for the room first")
  320. return
  321. }
  322. var encryptionEvent event.EncryptionEventContent
  323. err = ce.Bot.StateEvent(ce.RoomID, event.StateEncryption, "", &encryptionEvent)
  324. if err != nil && !errors.Is(err, mautrix.MNotFound) {
  325. ce.Reply("Failed to get room encryption status")
  326. return
  327. }
  328. var participants []types.JID
  329. participantDedup := make(map[types.JID]bool)
  330. participantDedup[ce.User.JID.ToNonAD()] = true
  331. participantDedup[types.EmptyJID] = true
  332. for userID := range members.Joined {
  333. jid, ok := handler.bridge.ParsePuppetMXID(userID)
  334. if !ok {
  335. user := handler.bridge.GetUserByMXID(userID)
  336. if user != nil && !user.JID.IsEmpty() {
  337. jid = user.JID.ToNonAD()
  338. }
  339. }
  340. if !participantDedup[jid] {
  341. participantDedup[jid] = true
  342. participants = append(participants, jid)
  343. }
  344. }
  345. handler.log.Infofln("Creating group for %s with name %s and participants %+v", ce.RoomID, roomNameEvent.Name, participants)
  346. resp, err := ce.User.Client.CreateGroup(roomNameEvent.Name, participants)
  347. if err != nil {
  348. ce.Reply("Failed to create group: %v", err)
  349. return
  350. }
  351. portal := ce.User.GetPortalByJID(resp.JID)
  352. portal.roomCreateLock.Lock()
  353. defer portal.roomCreateLock.Unlock()
  354. if len(portal.MXID) != 0 {
  355. portal.log.Warnln("Detected race condition in room creation")
  356. // TODO race condition, clean up the old room
  357. }
  358. portal.MXID = ce.RoomID
  359. portal.Name = roomNameEvent.Name
  360. portal.Encrypted = encryptionEvent.Algorithm == id.AlgorithmMegolmV1
  361. if !portal.Encrypted && handler.bridge.Config.Bridge.Encryption.Default {
  362. _, err = portal.MainIntent().SendStateEvent(portal.MXID, event.StateEncryption, "", &event.EncryptionEventContent{Algorithm: id.AlgorithmMegolmV1})
  363. if err != nil {
  364. portal.log.Warnln("Failed to enable encryption in room:", err)
  365. if errors.Is(err, mautrix.MForbidden) {
  366. ce.Reply("I don't seem to have permission to enable encryption in this room.")
  367. } else {
  368. ce.Reply("Failed to enable encryption in room: %v", err)
  369. }
  370. }
  371. portal.Encrypted = true
  372. }
  373. portal.Update()
  374. portal.UpdateBridgeInfo()
  375. ce.Reply("Successfully created WhatsApp group %s", portal.Key.JID)
  376. }
  377. func parseInviteMeta(meta map[string]interface{}) (jid, inviter types.JID, code string, expiration int64, ok bool) {
  378. var fieldFound bool
  379. code, fieldFound = meta["code"].(string)
  380. if !fieldFound {
  381. return
  382. }
  383. expirationStr, fieldFound := meta["expiration"].(string)
  384. if !fieldFound {
  385. return
  386. }
  387. inviterStr, fieldFound := meta["inviter"].(string)
  388. if !fieldFound {
  389. return
  390. }
  391. jidStr, fieldFound := meta["jid"].(string)
  392. if !fieldFound {
  393. return
  394. }
  395. var err error
  396. expiration, err = strconv.ParseInt(expirationStr, 10, 64)
  397. if err != nil {
  398. return
  399. }
  400. inviter, err = types.ParseJID(inviterStr)
  401. if err != nil {
  402. return
  403. }
  404. jid, err = types.ParseJID(jidStr)
  405. if err != nil {
  406. return
  407. }
  408. ok = true
  409. return
  410. }
  411. const cmdSetPowerLevelHelp = `set-pl [user ID] <power level> - Change the power level in a portal room. Only for bridge admins.`
  412. func (handler *CommandHandler) CommandSetPowerLevel(ce *CommandEvent) {
  413. if !ce.User.Admin {
  414. ce.Reply("Only bridge admins can use `set-pl`")
  415. return
  416. } else if ce.Portal == nil {
  417. ce.Reply("This is not a portal room")
  418. return
  419. }
  420. var level int
  421. var userID id.UserID
  422. var err error
  423. if len(ce.Args) == 1 {
  424. level, err = strconv.Atoi(ce.Args[0])
  425. if err != nil {
  426. ce.Reply("Invalid power level \"%s\"", ce.Args[0])
  427. return
  428. }
  429. userID = ce.User.MXID
  430. } else if len(ce.Args) == 2 {
  431. userID = id.UserID(ce.Args[0])
  432. _, _, err := userID.Parse()
  433. if err != nil {
  434. ce.Reply("Invalid user ID \"%s\"", ce.Args[0])
  435. return
  436. }
  437. level, err = strconv.Atoi(ce.Args[1])
  438. if err != nil {
  439. ce.Reply("Invalid power level \"%s\"", ce.Args[1])
  440. return
  441. }
  442. } else {
  443. ce.Reply("**Usage:** `set-pl [user] <level>`")
  444. return
  445. }
  446. intent := ce.Portal.MainIntent()
  447. _, err = intent.SetPowerLevel(ce.RoomID, userID, level)
  448. if err != nil {
  449. ce.Reply("Failed to set power levels: %v", err)
  450. }
  451. }
  452. const cmdLoginHelp = `login - Link the bridge to your WhatsApp account as a web client`
  453. // CommandLogin handles login command
  454. func (handler *CommandHandler) CommandLogin(ce *CommandEvent) {
  455. if ce.User.Session != nil {
  456. if ce.User.IsConnected() {
  457. ce.Reply("You're already logged in")
  458. } else {
  459. ce.Reply("You're already logged in. Perhaps you wanted to `reconnect`?")
  460. }
  461. return
  462. }
  463. qrChan, err := ce.User.Login(context.Background())
  464. if err != nil {
  465. ce.User.log.Errorf("Failed to log in:", err)
  466. ce.Reply("Failed to log in: %v", err)
  467. return
  468. }
  469. var qrEventID id.EventID
  470. for item := range qrChan {
  471. switch item.Event {
  472. case whatsmeow.QRChannelSuccess.Event:
  473. jid := ce.User.Client.Store.ID
  474. ce.Reply("Successfully logged in as +%s (device #%d)", jid.User, jid.Device)
  475. case whatsmeow.QRChannelTimeout.Event:
  476. ce.Reply("QR code timed out. Please restart the login.")
  477. case whatsmeow.QRChannelErrUnexpectedEvent.Event:
  478. ce.Reply("Failed to log in: unexpected connection event from server")
  479. case whatsmeow.QRChannelClientOutdated.Event:
  480. ce.Reply("Failed to log in: outdated client. The bridge must be updated to continue.")
  481. case whatsmeow.QRChannelScannedWithoutMultidevice.Event:
  482. ce.Reply("Please enable the WhatsApp multidevice beta and scan the QR code again.")
  483. case "error":
  484. ce.Reply("Failed to log in: %v", item.Error)
  485. case "code":
  486. qrEventID = ce.User.sendQR(ce, item.Code, qrEventID)
  487. }
  488. }
  489. _, _ = ce.Bot.RedactEvent(ce.RoomID, qrEventID)
  490. }
  491. func (user *User) sendQR(ce *CommandEvent, code string, prevEvent id.EventID) id.EventID {
  492. url, ok := user.uploadQR(ce, code)
  493. if !ok {
  494. return prevEvent
  495. }
  496. content := event.MessageEventContent{
  497. MsgType: event.MsgImage,
  498. Body: code,
  499. URL: url.CUString(),
  500. }
  501. if len(prevEvent) != 0 {
  502. content.SetEdit(prevEvent)
  503. }
  504. resp, err := ce.Bot.SendMessageEvent(ce.RoomID, event.EventMessage, &content)
  505. if err != nil {
  506. user.log.Errorln("Failed to send edited QR code to user:", err)
  507. } else if len(prevEvent) == 0 {
  508. prevEvent = resp.EventID
  509. }
  510. return prevEvent
  511. }
  512. func (user *User) uploadQR(ce *CommandEvent, code string) (id.ContentURI, bool) {
  513. qrCode, err := qrcode.Encode(code, qrcode.Low, 256)
  514. if err != nil {
  515. user.log.Errorln("Failed to encode QR code:", err)
  516. ce.Reply("Failed to encode QR code: %v", err)
  517. return id.ContentURI{}, false
  518. }
  519. bot := user.bridge.AS.BotClient()
  520. resp, err := bot.UploadBytes(qrCode, "image/png")
  521. if err != nil {
  522. user.log.Errorln("Failed to upload QR code:", err)
  523. ce.Reply("Failed to upload QR code: %v", err)
  524. return id.ContentURI{}, false
  525. }
  526. return resp.ContentURI, true
  527. }
  528. const cmdLogoutHelp = `logout - Unlink the bridge from your WhatsApp account`
  529. // CommandLogout handles !logout command
  530. func (handler *CommandHandler) CommandLogout(ce *CommandEvent) {
  531. if ce.User.Session == nil {
  532. ce.Reply("You're not logged in.")
  533. return
  534. } else if !ce.User.IsLoggedIn() {
  535. ce.Reply("You are not connected to WhatsApp. Use the `reconnect` command to reconnect, or `delete-session` to forget all login information.")
  536. return
  537. }
  538. puppet := handler.bridge.GetPuppetByJID(ce.User.JID)
  539. if puppet.CustomMXID != "" {
  540. err := puppet.SwitchCustomMXID("", "")
  541. if err != nil {
  542. ce.User.log.Warnln("Failed to logout-matrix while logging out of WhatsApp:", err)
  543. }
  544. }
  545. err := ce.User.Client.Logout()
  546. if err != nil {
  547. ce.User.log.Warnln("Error while logging out:", err)
  548. ce.Reply("Unknown error while logging out: %v", err)
  549. return
  550. }
  551. ce.User.Session = nil
  552. ce.User.removeFromJIDMap(StateLoggedOut)
  553. ce.User.DeleteConnection()
  554. ce.User.DeleteSession()
  555. ce.Reply("Logged out successfully.")
  556. }
  557. const cmdToggleHelp = `toggle <presence|receipts|all> - Toggle bridging of presence or read receipts`
  558. func (handler *CommandHandler) CommandToggle(ce *CommandEvent) {
  559. if len(ce.Args) == 0 || (ce.Args[0] != "presence" && ce.Args[0] != "receipts" && ce.Args[0] != "all") {
  560. ce.Reply("**Usage:** `toggle <presence|receipts|all>`")
  561. return
  562. }
  563. if ce.User.Session == nil {
  564. ce.Reply("You're not logged in.")
  565. return
  566. }
  567. customPuppet := handler.bridge.GetPuppetByCustomMXID(ce.User.MXID)
  568. if customPuppet == nil {
  569. ce.Reply("You're not logged in with your Matrix account.")
  570. return
  571. }
  572. if ce.Args[0] == "presence" || ce.Args[0] == "all" {
  573. customPuppet.EnablePresence = !customPuppet.EnablePresence
  574. var newPresence types.Presence
  575. if customPuppet.EnablePresence {
  576. newPresence = types.PresenceAvailable
  577. ce.Reply("Enabled presence bridging")
  578. } else {
  579. newPresence = types.PresenceUnavailable
  580. ce.Reply("Disabled presence bridging")
  581. }
  582. if ce.User.IsLoggedIn() {
  583. err := ce.User.Client.SendPresence(newPresence)
  584. if err != nil {
  585. ce.User.log.Warnln("Failed to set presence:", err)
  586. }
  587. }
  588. }
  589. if ce.Args[0] == "receipts" || ce.Args[0] == "all" {
  590. customPuppet.EnableReceipts = !customPuppet.EnableReceipts
  591. if customPuppet.EnableReceipts {
  592. ce.Reply("Enabled read receipt bridging")
  593. } else {
  594. ce.Reply("Disabled read receipt bridging")
  595. }
  596. }
  597. customPuppet.Update()
  598. }
  599. const cmdDeleteSessionHelp = `delete-session - Delete session information and disconnect from WhatsApp without sending a logout request`
  600. func (handler *CommandHandler) CommandDeleteSession(ce *CommandEvent) {
  601. if ce.User.Session == nil && ce.User.Client == nil {
  602. ce.Reply("Nothing to purge: no session information stored and no active connection.")
  603. return
  604. }
  605. ce.User.removeFromJIDMap(StateLoggedOut)
  606. ce.User.DeleteConnection()
  607. ce.User.DeleteSession()
  608. ce.Reply("Session information purged")
  609. }
  610. const cmdReconnectHelp = `reconnect - Reconnect to WhatsApp`
  611. func (handler *CommandHandler) CommandReconnect(ce *CommandEvent) {
  612. if ce.User.Client == nil {
  613. if ce.User.Session == nil {
  614. ce.Reply("You're not logged into WhatsApp. Please log in first.")
  615. } else {
  616. ce.User.Connect()
  617. ce.Reply("Started connecting to WhatsApp")
  618. }
  619. } else {
  620. ce.User.DeleteConnection()
  621. ce.User.sendBridgeState(BridgeState{StateEvent: StateTransientDisconnect, Error: WANotConnected})
  622. ce.User.Connect()
  623. ce.Reply("Restarted connection to WhatsApp")
  624. }
  625. }
  626. const cmdDisconnectHelp = `disconnect - Disconnect from WhatsApp (without logging out)`
  627. func (handler *CommandHandler) CommandDisconnect(ce *CommandEvent) {
  628. if ce.User.Client == nil {
  629. ce.Reply("You don't have a WhatsApp connection.")
  630. return
  631. }
  632. ce.User.DeleteConnection()
  633. ce.Reply("Successfully disconnected. Use the `reconnect` command to reconnect.")
  634. ce.User.sendBridgeState(BridgeState{StateEvent: StateBadCredentials, Error: WANotConnected})
  635. }
  636. const cmdPingHelp = `ping - Check your connection to WhatsApp.`
  637. func (handler *CommandHandler) CommandPing(ce *CommandEvent) {
  638. if ce.User.Session == nil {
  639. if ce.User.Client != nil {
  640. ce.Reply("Connected to WhatsApp, but not logged in.")
  641. } else {
  642. ce.Reply("You're not logged into WhatsApp.")
  643. }
  644. } else if ce.User.Client == nil || !ce.User.Client.IsConnected() {
  645. 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)
  646. } else {
  647. ce.Reply("Logged in as +%s (device #%d), connection to WhatsApp OK (probably)", ce.User.JID.User, ce.User.JID.Device)
  648. }
  649. }
  650. const cmdHelpHelp = `help - Prints this help`
  651. // CommandHelp handles help command
  652. func (handler *CommandHandler) CommandHelp(ce *CommandEvent) {
  653. cmdPrefix := ""
  654. if ce.User.ManagementRoom != ce.RoomID {
  655. cmdPrefix = handler.bridge.Config.Bridge.CommandPrefix + " "
  656. }
  657. ce.Reply("* " + strings.Join([]string{
  658. cmdPrefix + cmdHelpHelp,
  659. cmdPrefix + cmdVersionHelp,
  660. cmdPrefix + cmdLoginHelp,
  661. cmdPrefix + cmdLogoutHelp,
  662. cmdPrefix + cmdDeleteSessionHelp,
  663. cmdPrefix + cmdReconnectHelp,
  664. cmdPrefix + cmdDisconnectHelp,
  665. cmdPrefix + cmdPingHelp,
  666. cmdPrefix + cmdSetRelayHelp,
  667. cmdPrefix + cmdUnsetRelayHelp,
  668. cmdPrefix + cmdLoginMatrixHelp,
  669. cmdPrefix + cmdPingMatrixHelp,
  670. cmdPrefix + cmdLogoutMatrixHelp,
  671. cmdPrefix + cmdToggleHelp,
  672. cmdPrefix + cmdListHelp,
  673. cmdPrefix + cmdSearchHelp,
  674. cmdPrefix + cmdSyncHelp,
  675. cmdPrefix + cmdOpenHelp,
  676. cmdPrefix + cmdPMHelp,
  677. cmdPrefix + cmdInviteLinkHelp,
  678. cmdPrefix + cmdResolveLinkHelp,
  679. cmdPrefix + cmdJoinHelp,
  680. cmdPrefix + cmdCreateHelp,
  681. cmdPrefix + cmdSetPowerLevelHelp,
  682. cmdPrefix + cmdDeletePortalHelp,
  683. cmdPrefix + cmdDeleteAllPortalsHelp,
  684. }, "\n* "))
  685. }
  686. func canDeletePortal(portal *Portal, userID id.UserID) bool {
  687. members, err := portal.MainIntent().JoinedMembers(portal.MXID)
  688. if err != nil {
  689. portal.log.Errorfln("Failed to get joined members to check if portal can be deleted by %s: %v", userID, err)
  690. return false
  691. }
  692. for otherUser := range members.Joined {
  693. _, isPuppet := portal.bridge.ParsePuppetMXID(otherUser)
  694. if isPuppet || otherUser == portal.bridge.Bot.UserID || otherUser == userID {
  695. continue
  696. }
  697. user := portal.bridge.GetUserByMXID(otherUser)
  698. if user != nil && user.Session != nil {
  699. return false
  700. }
  701. }
  702. return true
  703. }
  704. const cmdDeletePortalHelp = `delete-portal - Delete the current portal. If the portal is used by other people, this is limited to bridge admins.`
  705. func (handler *CommandHandler) CommandDeletePortal(ce *CommandEvent) {
  706. if ce.Portal == nil {
  707. ce.Reply("You must be in a portal room to use that command")
  708. return
  709. }
  710. if !ce.User.Admin && !canDeletePortal(ce.Portal, ce.User.MXID) {
  711. ce.Reply("Only bridge admins can delete portals with other Matrix users")
  712. return
  713. }
  714. ce.Portal.log.Infoln(ce.User.MXID, "requested deletion of portal.")
  715. ce.Portal.Delete()
  716. ce.Portal.Cleanup(false)
  717. }
  718. const cmdDeleteAllPortalsHelp = `delete-all-portals - Delete all portals.`
  719. func (handler *CommandHandler) CommandDeleteAllPortals(ce *CommandEvent) {
  720. portals := handler.bridge.GetAllPortals()
  721. var portalsToDelete []*Portal
  722. if ce.User.Admin {
  723. portalsToDelete = portals
  724. } else {
  725. portalsToDelete = portals[:0]
  726. for _, portal := range portals {
  727. if canDeletePortal(portal, ce.User.MXID) {
  728. portalsToDelete = append(portalsToDelete, portal)
  729. }
  730. }
  731. }
  732. leave := func(portal *Portal) {
  733. if len(portal.MXID) > 0 {
  734. _, _ = portal.MainIntent().KickUser(portal.MXID, &mautrix.ReqKickUser{
  735. Reason: "Deleting portal",
  736. UserID: ce.User.MXID,
  737. })
  738. }
  739. }
  740. customPuppet := handler.bridge.GetPuppetByCustomMXID(ce.User.MXID)
  741. if customPuppet != nil && customPuppet.CustomIntent() != nil {
  742. intent := customPuppet.CustomIntent()
  743. leave = func(portal *Portal) {
  744. if len(portal.MXID) > 0 {
  745. _, _ = intent.LeaveRoom(portal.MXID)
  746. _, _ = intent.ForgetRoom(portal.MXID)
  747. }
  748. }
  749. }
  750. ce.Reply("Found %d portals, deleting...", len(portalsToDelete))
  751. for _, portal := range portalsToDelete {
  752. portal.Delete()
  753. leave(portal)
  754. }
  755. ce.Reply("Finished deleting portal info. Now cleaning up rooms in background.")
  756. go func() {
  757. for _, portal := range portalsToDelete {
  758. portal.Cleanup(false)
  759. }
  760. ce.Reply("Finished background cleanup of deleted portal rooms.")
  761. }()
  762. }
  763. const cmdListHelp = `list <contacts|groups> [page] [items per page] - Get a list of all contacts and groups.`
  764. func matchesQuery(str string, query string) bool {
  765. if query == "" {
  766. return true
  767. }
  768. return strings.Contains(strings.ToLower(str), query)
  769. }
  770. func formatContacts(bridge *Bridge, input map[types.JID]types.ContactInfo, query string) (result []string) {
  771. hasQuery := len(query) > 0
  772. for jid, contact := range input {
  773. if len(contact.FullName) == 0 {
  774. continue
  775. }
  776. puppet := bridge.GetPuppetByJID(jid)
  777. pushName := contact.PushName
  778. if len(pushName) == 0 {
  779. pushName = contact.FullName
  780. }
  781. if !hasQuery || matchesQuery(pushName, query) || matchesQuery(contact.FullName, query) || matchesQuery(jid.User, query) {
  782. result = append(result, fmt.Sprintf("* %s / [%s](https://matrix.to/#/%s) - `+%s`", contact.FullName, pushName, puppet.MXID, jid.User))
  783. }
  784. }
  785. sort.Sort(sort.StringSlice(result))
  786. return
  787. }
  788. func formatGroups(input []*types.GroupInfo, query string) (result []string) {
  789. hasQuery := len(query) > 0
  790. for _, group := range input {
  791. if !hasQuery || matchesQuery(group.GroupName.Name, query) || matchesQuery(group.JID.User, query) {
  792. result = append(result, fmt.Sprintf("* %s - `%s`", group.GroupName.Name, group.JID.User))
  793. }
  794. }
  795. sort.Sort(sort.StringSlice(result))
  796. return
  797. }
  798. func (handler *CommandHandler) CommandList(ce *CommandEvent) {
  799. if len(ce.Args) == 0 {
  800. ce.Reply("**Usage:** `list <contacts|groups> [page] [items per page]`")
  801. return
  802. }
  803. mode := strings.ToLower(ce.Args[0])
  804. if mode[0] != 'g' && mode[0] != 'c' {
  805. ce.Reply("**Usage:** `list <contacts|groups> [page] [items per page]`")
  806. return
  807. }
  808. var err error
  809. page := 1
  810. max := 100
  811. if len(ce.Args) > 1 {
  812. page, err = strconv.Atoi(ce.Args[1])
  813. if err != nil || page <= 0 {
  814. ce.Reply("\"%s\" isn't a valid page number", ce.Args[1])
  815. return
  816. }
  817. }
  818. if len(ce.Args) > 2 {
  819. max, err = strconv.Atoi(ce.Args[2])
  820. if err != nil || max <= 0 {
  821. ce.Reply("\"%s\" isn't a valid number of items per page", ce.Args[2])
  822. return
  823. } else if max > 400 {
  824. ce.Reply("Warning: a high number of items per page may fail to send a reply")
  825. }
  826. }
  827. contacts := mode[0] == 'c'
  828. typeName := "Groups"
  829. var result []string
  830. if contacts {
  831. typeName = "Contacts"
  832. contactList, err := ce.User.Client.Store.Contacts.GetAllContacts()
  833. if err != nil {
  834. ce.Reply("Failed to get contacts: %s", err)
  835. return
  836. }
  837. result = formatContacts(ce.User.bridge, contactList, "")
  838. } else {
  839. groupList, err := ce.User.Client.GetJoinedGroups()
  840. if err != nil {
  841. ce.Reply("Failed to get groups: %s", err)
  842. return
  843. }
  844. result = formatGroups(groupList, "")
  845. }
  846. if len(result) == 0 {
  847. ce.Reply("No %s found", strings.ToLower(typeName))
  848. return
  849. }
  850. pages := int(math.Ceil(float64(len(result)) / float64(max)))
  851. if (page-1)*max >= len(result) {
  852. if pages == 1 {
  853. ce.Reply("There is only 1 page of %s", strings.ToLower(typeName))
  854. } else {
  855. ce.Reply("There are %d pages of %s", pages, strings.ToLower(typeName))
  856. }
  857. return
  858. }
  859. lastIndex := page * max
  860. if lastIndex > len(result) {
  861. lastIndex = len(result)
  862. }
  863. result = result[(page-1)*max : lastIndex]
  864. ce.Reply("### %s (page %d of %d)\n\n%s", typeName, page, pages, strings.Join(result, "\n"))
  865. }
  866. const cmdSearchHelp = `search <query> - Search for contacts or groups.`
  867. func (handler *CommandHandler) CommandSearch(ce *CommandEvent) {
  868. if len(ce.Args) == 0 {
  869. ce.Reply("**Usage:** `search <query>`")
  870. return
  871. }
  872. contactList, err := ce.User.Client.Store.Contacts.GetAllContacts()
  873. if err != nil {
  874. ce.Reply("Failed to get contacts: %s", err)
  875. return
  876. }
  877. groupList, err := ce.User.Client.GetJoinedGroups()
  878. if err != nil {
  879. ce.Reply("Failed to get groups: %s", err)
  880. return
  881. }
  882. query := strings.ToLower(strings.TrimSpace(strings.Join(ce.Args, " ")))
  883. formattedContacts := strings.Join(formatContacts(ce.User.bridge, contactList, query), "\n")
  884. formattedGroups := strings.Join(formatGroups(groupList, query), "\n")
  885. result := make([]string, 0, 2)
  886. if len(formattedContacts) > 0 {
  887. result = append(result, "### Contacts\n\n"+formattedContacts)
  888. }
  889. if len(formattedGroups) > 0 {
  890. result = append(result, "### Groups\n\n"+formattedGroups)
  891. }
  892. if len(result) == 0 {
  893. ce.Reply("No contacts or groups found")
  894. return
  895. }
  896. ce.Reply(strings.Join(result, "\n\n"))
  897. }
  898. const cmdOpenHelp = `open <_group JID_> - Open a group chat portal.`
  899. func (handler *CommandHandler) CommandOpen(ce *CommandEvent) {
  900. if len(ce.Args) == 0 {
  901. ce.Reply("**Usage:** `open <group JID>`")
  902. return
  903. }
  904. var jid types.JID
  905. if strings.ContainsRune(ce.Args[0], '@') {
  906. jid, _ = types.ParseJID(ce.Args[0])
  907. } else {
  908. jid = types.NewJID(ce.Args[0], types.GroupServer)
  909. }
  910. if jid.Server != types.GroupServer || (!strings.ContainsRune(jid.User, '-') && len(jid.User) < 15) {
  911. ce.Reply("That does not look like a group JID")
  912. return
  913. }
  914. info, err := ce.User.Client.GetGroupInfo(jid)
  915. if err != nil {
  916. ce.Reply("Failed to get group info: %v", err)
  917. return
  918. }
  919. handler.log.Debugln("Importing", jid, "for", ce.User.MXID)
  920. portal := ce.User.GetPortalByJID(info.JID)
  921. if len(portal.MXID) > 0 {
  922. portal.UpdateMatrixRoom(ce.User, info)
  923. ce.Reply("Portal room synced.")
  924. } else {
  925. err = portal.CreateMatrixRoom(ce.User, info, true)
  926. if err != nil {
  927. ce.Reply("Failed to create room: %v", err)
  928. } else {
  929. ce.Reply("Portal room created.")
  930. }
  931. }
  932. }
  933. const cmdPMHelp = `pm <_international phone number_> - Open a private chat with the given phone number.`
  934. func (handler *CommandHandler) CommandPM(ce *CommandEvent) {
  935. if len(ce.Args) == 0 {
  936. ce.Reply("**Usage:** `pm <international phone number>`")
  937. return
  938. }
  939. user := ce.User
  940. number := strings.Join(ce.Args, "")
  941. resp, err := ce.User.Client.IsOnWhatsApp([]string{number})
  942. if err != nil {
  943. ce.Reply("Failed to check if user is on WhatsApp: %v", err)
  944. return
  945. } else if len(resp) == 0 {
  946. ce.Reply("Didn't get a response to checking if the user is on WhatsApp")
  947. return
  948. }
  949. targetUser := resp[0]
  950. if !targetUser.IsIn {
  951. ce.Reply("The server said +%s is not on WhatsApp", targetUser.JID.User)
  952. return
  953. }
  954. portal, puppet, justCreated, err := user.StartPM(targetUser.JID, "manual PM command")
  955. if err != nil {
  956. ce.Reply("Failed to create portal room: %v", err)
  957. } else if !justCreated {
  958. ce.Reply("You already have a private chat portal with +%s at [%s](https://matrix.to/#/%s)", puppet.JID.User, puppet.Displayname, portal.MXID)
  959. } else {
  960. ce.Reply("Created portal room with +%s and invited you to it.", puppet.JID.User)
  961. }
  962. }
  963. const cmdSyncHelp = `sync <appstate/contacts/groups/space> [--create-portals] - Synchronize data from WhatsApp.`
  964. func (handler *CommandHandler) CommandSync(ce *CommandEvent) {
  965. if len(ce.Args) == 0 {
  966. ce.Reply("**Usage:** `sync <appstate/contacts/groups/space> [--create-portals]`")
  967. return
  968. }
  969. args := strings.ToLower(strings.Join(ce.Args, " "))
  970. contacts := strings.Contains(args, "contacts")
  971. appState := strings.Contains(args, "appstate")
  972. space := strings.Contains(args, "space")
  973. groups := strings.Contains(args, "groups") || space
  974. createPortals := strings.Contains(args, "--create-portals")
  975. if appState {
  976. for _, name := range appstate.AllPatchNames {
  977. err := ce.User.Client.FetchAppState(name, true, false)
  978. if err != nil {
  979. ce.Reply("Error syncing app state %s: %v", name, err)
  980. } else if name == appstate.WAPatchCriticalUnblockLow {
  981. ce.Reply("Synced app state %s, contact sync running in background", name)
  982. } else {
  983. ce.Reply("Synced app state %s", name)
  984. }
  985. }
  986. } else if contacts {
  987. err := ce.User.ResyncContacts()
  988. if err != nil {
  989. ce.Reply("Error resyncing contacts: %v", err)
  990. } else {
  991. ce.Reply("Resynced contacts")
  992. }
  993. }
  994. if space {
  995. if !ce.Bridge.Config.Bridge.PersonalFilteringSpaces {
  996. ce.Reply("Personal filtering spaces are not enabled on this instance of the bridge")
  997. return
  998. }
  999. keys := ce.Bridge.DB.Portal.FindPrivateChatsNotInSpace(ce.User.JID)
  1000. count := 0
  1001. for _, key := range keys {
  1002. portal := ce.Bridge.GetPortalByJID(key)
  1003. portal.addToSpace(ce.User)
  1004. count++
  1005. }
  1006. plural := "s"
  1007. if count == 1 {
  1008. plural = ""
  1009. }
  1010. ce.Reply("Added %d DM room%s to space", count, plural)
  1011. }
  1012. if groups {
  1013. err := ce.User.ResyncGroups(createPortals)
  1014. if err != nil {
  1015. ce.Reply("Error resyncing groups: %v", err)
  1016. } else {
  1017. ce.Reply("Resynced groups")
  1018. }
  1019. }
  1020. }
  1021. const cmdLoginMatrixHelp = `login-matrix <_access token_> - Replace your WhatsApp account's Matrix puppet with your real Matrix account.`
  1022. func (handler *CommandHandler) CommandLoginMatrix(ce *CommandEvent) {
  1023. if len(ce.Args) == 0 {
  1024. ce.Reply("**Usage:** `login-matrix <access token>`")
  1025. return
  1026. }
  1027. puppet := handler.bridge.GetPuppetByJID(ce.User.JID)
  1028. err := puppet.SwitchCustomMXID(ce.Args[0], ce.User.MXID)
  1029. if err != nil {
  1030. ce.Reply("Failed to switch puppet: %v", err)
  1031. return
  1032. }
  1033. ce.Reply("Successfully switched puppet")
  1034. }
  1035. const cmdPingMatrixHelp = `ping-matrix - Check if your double puppet is working correctly.`
  1036. func (handler *CommandHandler) CommandPingMatrix(ce *CommandEvent) {
  1037. puppet := handler.bridge.GetPuppetByCustomMXID(ce.User.MXID)
  1038. if puppet == nil || puppet.CustomIntent() == nil {
  1039. ce.Reply("You have not changed your WhatsApp account's Matrix puppet.")
  1040. return
  1041. }
  1042. resp, err := puppet.CustomIntent().Whoami()
  1043. if err != nil {
  1044. ce.Reply("Failed to validate Matrix login: %v", err)
  1045. } else {
  1046. ce.Reply("Confirmed valid access token for %s / %s", resp.UserID, resp.DeviceID)
  1047. }
  1048. }
  1049. const cmdLogoutMatrixHelp = `logout-matrix - Switch your WhatsApp account's Matrix puppet back to the default one.`
  1050. func (handler *CommandHandler) CommandLogoutMatrix(ce *CommandEvent) {
  1051. puppet := handler.bridge.GetPuppetByCustomMXID(ce.User.MXID)
  1052. if puppet == nil || puppet.CustomIntent() == nil {
  1053. ce.Reply("You had not changed your WhatsApp account's Matrix puppet.")
  1054. return
  1055. }
  1056. err := puppet.SwitchCustomMXID("", "")
  1057. if err != nil {
  1058. ce.Reply("Failed to remove custom puppet: %v", err)
  1059. return
  1060. }
  1061. ce.Reply("Successfully removed custom puppet")
  1062. }