commands.go 36 KB

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