戈 惠鈺

戈 惠鈺

1678900500

Mac 微信初学者入门

在本指南中,我们将学习如何在 Mac 上使用微信。如今,消息应用程序是我们大多数人交流的方式。它们不使用传统的电信基础设施,而是允许您通过 Internet 进行通信,因此随着 3G 和 LTE 网络的扩展,它们的受欢迎程度急剧增加。 

聊天应用程序不仅取代了传统的电话和短信,而且通过添加视频通话、会议、群发消息、文件共享、系统支付、状态更新、聊天机器人等,从根本上扩展了您的沟通方式。 

总的来说,消息传递市场每天都在变得越来越饱和。有 Facebook Messenger、WhatsApp、Skype、Telegram、Viber、Snapchat、Instagram、Slack、Signal、Line 等。通常情况下,即时通讯应用程序几乎只在某个地理市场中使用。例如,对于中国来说是微信。

什么是微信?

微信是中国科技巨头腾讯于 2011 年开发的一款消息应用程序。2018 年,微信被评为全球最大的独立应用程序,活跃用户超过 10 亿。除了网络效应之外,该应用程序的流行还可以归因于它与几乎所有类型的业务交易的紧密集成。

微信用户可以通过该应用支付账单、购买商品和服务、向联系人汇款,甚至在商店付款。由于微信作为一个平台,越来越多的供应商将他们的服务添加到应用程序中,使其在日常生活中更加有用。 

您可以下载 Mac、Windows、iOS、Android 版微信,也可以在线使用。让我们看看为什么您需要 Mac 版微信应用程序以及如何最好地使用它。 

如何使用 Mac 版微信应用程序

在使用Mac微信之前,你需要下载手机版的微信,因为它是用来验证用户身份的,类似于WhatsApp。微信应用程序可在 App Store 和 Google Play 上找到。

获取微信移动应用程序并创建免费帐户后,您可以从微信网站或 App Store 下载 Mac 版微信。您必须运行 OS X 10.11 El Capitan 或更高版本才能运行该应用程序。 

当你打开微信 Mac 应用程序时,你会看到一个用于登录微信的二维码。在手机上打开微信,从底部菜单中选择探索,然后扫描二维码。将您的手机对准 Mac 上的代码并登录。

现在你可以在 Mac 上使用微信了,免去了不断切换设备的麻烦,更轻松地共享文档和文件。不过需要注意的是,微信Mac版不支持音视频通话和朋友圈。但您仍然可以发送消息、文件和视频。 

下载 Mac 版微信 App

如何在线使用微信

如果不想下载 Mac 版微信,也可以使用微信网页版。Mac 上的身份验证过程非常相似: 

访问 web.wechat.com

用手机扫描二维码

去谈谈! 

从微信在线应用扫描二维码WeChat 网络应用程序支持与 Mac 上的 WeChat 相同的功能,并且可以从任何计算机访问,包括公共或工作计算机(如果您的下载受限)。在某些情况下,当您无法直接下载 Mac 版微信但想在您自己的环境中使用它时,您可以将 Web 应用转移到您的 Mac 上。 

Unite是一款独特的工具,可将几乎所有网站转变为渐进式 Mac 应用程序。使用 Safari WebKit 引擎,此扩展将网页与所有浏览器软件分开,并添加了自己的外观。您可以自定义应用程序的外观和感觉,包括标题栏的颜色和 Dock 中的图标。 

要使用 Unite 创建应用程序,只需输入应用程序的名称及其 URL 和图标源。和这个!您现在拥有一个全新的全功能 Mac 应用程序。

组队为 Mac 打造微信应用

绑定

从网站创建应用程序

绑定

了解更多

如何同时访问多个信使

微信可能不是您使用的唯一应用程序。即使在中国,另一个消息应用程序 QQ 也拥有近 10 亿用户。在世界其他地区,面对来自 WhatsApp、Facebook Messenger 和 Telegram 的竞争,微信的相关性就更小了。 

因此,如果您经常在多个应用程序之间切换并收到各种通知,生活就会变得非常复杂。你不需要那么大的压力。相反,只需使用专门设计的解决方案将您所有的信使合二为一。 

IM+是世界上最好的消息聚合器。IM+ 兼容 18 种聊天应用程序等,包括微信、WhatsApp、Facebook Messenger、Skype、Zoom、Slack 和 Instagram,将所有不同的界面整合到一个方便的应用程序窗口中,因此您无需在它们之间切换。同时,该应用程序可使用所有相同的功能、快捷方式和文件托管。 

此外,您可以在 IM+ 应用程序中通过分配特定标签、自定义通知和设置状态更新轻松分离您的工作和家庭生活。 

适用于 Mac 的 IM+ 消息传递应用程序

即时消息+

将所有使者合而为一

即时消息+

了解更多

如何使您的聊天私密

对于 Mac 版微信应用程序,与任何存储您的个人信息的软件一样,保持对话的私密性和安全性至关重要。 

虽然疫情期间我们不再在公共场所使用 Mac,但使用 Mac 时周围通常人不多,如果我们不小心进入,我们的电脑更容易被盗。等一下。 

One Switch是 Mac 不可或缺的实用工具。这个简单的应用程序位于菜单栏中,可在几秒钟内锁定屏幕。就如此容易。 

开关挡住了键盘和屏幕

转变

快速访问 macOS 功能

转变

了解更多

如您所见,微信是亚洲领先的消息应用程序,当您拥有移动应用程序时,下载 Mac 版微信非常容易。更好的是,您可以通过在线登录微信并使用 Unite 创建新的原生 Mac 应用程序来避免工作场所的任何限制。或者,您可以将微信与 IM+ 上的所有其他信使结合使用。不要忘记使用 One Switch 保护您的隐私。 

最重要的是,作为 Setapp 试用版的一部分,Unite、IM+ 和 One Switch 可供您完全免费使用 7 天,Setapp 是一个 Mac 平台,每个场景都有近 200 个高级 Mac 应用程序。每当您遇到问题时,只需打开 Setapp 并找到解决方案 - 您会惊讶地发现使用手头的正确工具避免低效率是多么容易。并在 Setapp 中浏览所有 iOS 配套应用程序,这样您就可以去任何地方而无需改变您的工作流程。

来源: https: //setapp.com

#mac #wechat 

Mac 微信初学者入门

Usando o WeChat no Mac para Iniciantes

Neste tutorial, aprendemos sobre como usar o WeChat no Mac. Os aplicativos de mensagens são a maneira como a maioria de nós se comunica hoje em dia. Em vez de usar a infraestrutura tradicional de telecomunicações, eles permitem a conversação pela internet, por isso sua popularidade está aumentando acentuadamente com a expansão das redes 3G e LTE. 

Os aplicativos de bate-papo não apenas substituem as chamadas telefônicas e SMS tradicionais, mas também expandem radicalmente as formas de comunicação, adicionando videochamadas, chamadas em conferência, mensagens em grupo, compartilhamento de arquivos, pagamentos do sistema, atualizações de status, chatbots etc. 

No geral, o mercado de mensagens está ficando cada vez mais saturado a cada dia. Existem Facebook Messenger, WhatsApp, Skype, Telegram, Viber, Snapchat, Instagram, Slack, Signal, Line, etc. Normalmente, um aplicativo de mensagens instantâneas estará quase exclusivamente em um determinado mercado geográfico. Para a China, por exemplo, é o WeChat.

O que é o WeChat?

O WeChat é um aplicativo de mensagens desenvolvido pela gigante tecnológica chinesa Tencent em 2011. Em 2018, o WeChat foi descrito como o maior aplicativo independente do mundo, com mais de um bilhão de usuários ativos. Além dos efeitos de rede, a popularidade do aplicativo pode ser atribuída à sua forte integração com quase todos os tipos de transações comerciais.

Os usuários do WeChat podem pagar contas, comprar produtos e serviços, enviar dinheiro para seus contatos e até mesmo pagar na loja - tudo por meio do aplicativo. Como o WeChat atua como uma plataforma, mais e mais provedores estão adicionando seus serviços ao aplicativo, tornando-o mais útil no dia a dia. 

Você pode baixar o WeChat para Mac, Windows, iOS, Android e também usá-lo online. Vamos ver por que você quer o aplicativo WeChat para Mac e como usá-lo melhor. 

Como usar o aplicativo WeChat para Mac

Antes de usar o Mac WeChat, você precisa baixar a versão móvel do aplicativo, pois ela é usada para autenticação do usuário, semelhante ao que o WhatsApp está fazendo. O aplicativo WeChat está disponível na App Store e no Google Play.

Depois de ter o aplicativo móvel WeChat e criar uma conta gratuita, você pode baixar o WeChat para Mac, no site do WeChat ou na App Store. Você deve estar executando o OS X 10.11 El Capitan ou posterior para iniciar o aplicativo. 

Ao abrir o aplicativo WeChat para Mac, você verá um prompt de código QR de login do WeChat. Abra o WeChat no seu telefone, selecione Explorar no menu na parte inferior e, em seguida, digitalize o código QR. Aponte seu telefone para o código no seu Mac e entre.

Agora você pode usar o WeChat no seu Mac, o que evita que você alterne constantemente entre dispositivos e facilita o compartilhamento de documentos e arquivos. No entanto, observe que o WeChat para Mac não suporta chamadas de áudio e vídeo nem Moments. Mas você ainda pode enviar mensagens, arquivos e vídeos. 

Baixe o aplicativo WeChat para Mac

Como usar o WeChat online

Se você não está animado para baixar o WeChat para Mac, também pode usar o aplicativo da web WeChat. O processo de autenticação é muito semelhante ao Mac: 

Visite web.wechat.com

Escaneie o código QR com seu telefone

Vá conversar! 

escaneie o código QR do aplicativo online WeChatO aplicativo da Web WeChat oferece suporte à mesma funcionalidade do WeChat no Mac e pode ser acessado em qualquer computador, incluindo um computador público ou no trabalho, caso seus downloads sejam restritos. Em alguns casos, quando você não pode baixar o WeChat para Mac diretamente, mas ainda deseja usá-lo no ambiente nativo, pode portar o aplicativo da Web para o seu Mac. 

O Unite é uma ferramenta exclusiva para transformar praticamente qualquer site em um aplicativo Mac progressivo. Usando o mecanismo WebKit do Safari, esta extensão remove a página da web de todos os softwares de navegador e adiciona uma aparência e funcionalidade nativas. Você pode personalizar a aparência de seus aplicativos, incluindo a cor da barra de título e os ícones no Dock. 

Para criar um aplicativo com o Unite, basta inserir o nome do aplicativo junto com sua URL e a origem do ícone. É isso! Agora você tem um novo aplicativo Mac totalmente funcional.

Una-se para criar o aplicativo WeChat para Mac

unir

Criar um aplicativo a partir de um site

unir

Descubra mais

Como acessar vários mensageiros ao mesmo tempo

Provavelmente, o WeChat não é o único aplicativo que você usa. Mesmo na China, outro aplicativo de mensagens, o QQ, tem quase um bilhão de usuários. Em outras partes do mundo, o WeChat é ainda menos relevante diante da concorrência do WhatsApp, Facebook Messenger e Telegram. 

Então, se você está constantemente alternando entre vários aplicativos e recebendo todos os tipos de notificações, a vida pode ficar bem complicada. Você não precisa de tanto estresse. Em vez disso, basta usar uma solução criada especificamente para mesclar todos os seus mensageiros em um só. 

IM+ é o melhor agregador de mensagens do mundo. Compatível com 18 aplicativos de bate-papo e mais - incluindo WeChat, WhatsApp, Facebook Messenger, Skype, Zoom, Slack e Instagram - o IM+ combina todas as diferentes interfaces em uma janela de aplicativo conveniente para ajudar você a não ter que alternar continuamente. Ao mesmo tempo, o aplicativo funciona com todas as mesmas funções, atalhos e compartilhamento de arquivos. 

Além disso, você pode separar facilmente sua vida profissional e doméstica no aplicativo IM+, atribuindo tags específicas, personalizando notificações e definindo atualizações de status. 

Aplicativo de mensagens IM+ no Mac

mensagem instantânea +

Traga todos os mensageiros em um

mensagem instantânea +

Descubra mais

Como manter seus chats privados

Com o aplicativo WeChat para Mac, assim como qualquer outro software que armazena suas informações pessoais, é extremamente importante manter suas conversas privadas e seguras. 

Embora durante a pandemia não usemos mais Macs em público, quando os usamos, geralmente não há muitas pessoas por perto, o que aumenta a probabilidade de nossos computadores serem roubados se entrarmos acidentalmente. um minuto de distância. 

One Switch é o melhor utilitário para o seu Mac. Este aplicativo simples fica na barra de menus e bloqueia a tela em segundos. Tão simples como isso. 

Um interruptor bloqueia o teclado e a tela

uma troca

Acesse os recursos do macOS rapidamente

uma troca

Descubra mais

Como você pode ver, o WeChat é o aplicativo de mensagens líder na Ásia e baixar o WeChat para Mac é fácil quando você tem o aplicativo móvel. Melhor ainda, você pode evitar quaisquer restrições em seu local de trabalho fazendo login no WeChat online e criando um novo aplicativo nativo para Mac usando o Unite. Como alternativa, você pode combinar o WeChat com todos os seus outros mensageiros no IM+. E não se esqueça de manter sua privacidade intacta com o One Switch. 

O melhor de tudo é que Unite, IM+ e One Switch são totalmente gratuitos para você por sete dias por meio de uma avaliação do Setapp , uma plataforma Mac com quase 200 aplicativos Mac de primeira linha para todos os cenários. Sempre que você se deparar com um problema, basta abrir o Setapp e procurar uma solução — você ficará surpreso com a facilidade com que as ineficiências podem ser evitadas quando você tem a ferramenta certa em mãos. E veja todos os aplicativos iOS complementares no Setapp, para que você possa ir a qualquer lugar sem alterar seu fluxo de trabalho.

Fonte: https://setapp.com

#mac #wechat 

Usando o WeChat no Mac para Iniciantes

Использование WeChat на Mac для начинающих

В этом руководстве мы узнаем, как использовать WeChat на Mac. Приложения для обмена сообщениями — это способ общения большинства из нас в наши дни. Вместо использования традиционной телекоммуникационной инфраструктуры они позволяют общаться через Интернет, поэтому их популярность резко возрастает с расширением сетей 3G и LTE. 

Чат-приложения не только заменяют традиционные телефонные звонки и SMS, но и радикально расширяют способы общения, добавляя видеосвязь, конференц-связь, групповой обмен сообщениями, обмен файлами, системные платежи, обновления статуса, чат-боты и т. д. 

В целом рынок обмена сообщениями с каждым днем ​​становится все более и более насыщенным. Есть Facebook Messenger, WhatsApp, Skype, Telegram, Viber, Snapchat, Instagram, Slack, Signal, Line и др. Как правило, приложение для обмена мгновенными сообщениями будет почти исключительно на определенном географическом рынке. Например, для Китая это WeChat.

Что такое WeChat?

WeChat — это приложение для обмена сообщениями, разработанное китайским технологическим гигантом Tencent в 2011 году. В 2018 году WeChat был назван крупнейшим в мире независимым приложением с более чем миллиардом активных пользователей. Помимо сетевых эффектов, популярность приложения можно объяснить его тесной интеграцией практически со всеми типами бизнес-транзакций.

Пользователи WeChat могут оплачивать счета, покупать товары и услуги, отправлять деньги своим контактам и даже платить в магазине — и все это через приложение. Поскольку WeChat выступает в качестве платформы, все больше и больше провайдеров добавляют свои услуги в приложение, делая его более полезным в повседневной жизни. 

Вы можете скачать WeChat для Mac, Windows, iOS, Android, а также использовать его онлайн. Давайте посмотрим, почему вам нужно приложение WeChat для Mac и как его лучше всего использовать. 

Как использовать приложение WeChat для Mac

Прежде чем использовать Mac WeChat, вам необходимо загрузить мобильную версию приложения, так как оно используется для аутентификации пользователя, аналогично тому, что делает WhatsApp. Приложение WeChat доступно в App Store и Google Play.

Получив мобильное приложение WeChat и создав бесплатную учетную запись, вы можете загрузить WeChat для Mac с веб-сайта WeChat или из App Store. Вы должны использовать OS X 10.11 El Capitan или более позднюю версию, чтобы запустить приложение. 

Когда вы откроете приложение WeChat для Mac, вы увидите QR-код для входа в WeChat. Откройте WeChat на своем телефоне, выберите «Исследовать» в меню внизу, затем отсканируйте QR-код. Наведите телефон на код на Mac и войдите в систему.

Теперь вы можете использовать WeChat на своем Mac, что избавляет вас от необходимости постоянно переключаться между устройствами и упрощает обмен документами и файлами. Однако обратите внимание, что WeChat для Mac не поддерживает аудио- и видеозвонки или Моменты. Но вы по-прежнему можете отправлять сообщения, файлы и видео. 

Загрузите приложение WeChat для Mac

Как использовать WeChat онлайн

Если вы не хотите загружать WeChat для Mac, вы также можете использовать веб-приложение WeChat. Процесс аутентификации очень похож на Mac: 

Посетите web.wechat.com

Отсканируйте QR-код с помощью телефона

Иди говори! 

отсканируйте QR-код из онлайн-приложения WeChatВеб-приложение WeChat поддерживает те же функции, что и WeChat на Mac, и к нему можно получить доступ с любого компьютера, включая общедоступный или рабочий компьютер, если ваши загрузки ограничены. В некоторых случаях, когда вы не можете загрузить WeChat для Mac напрямую, но хотите использовать его в собственной среде, вы можете перенести веб-приложение на свой Mac. 

Unite — это уникальный инструмент для превращения практически любого веб-сайта в прогрессивное приложение для Mac. Используя движок Safari WebKit, это расширение отделяет веб-страницу от всего программного обеспечения браузера и добавляет собственный внешний вид. Вы можете настроить внешний вид своих приложений, включая цвет строки заголовка и значков в Dock. 

Чтобы создать приложение с помощью Unite, просто введите имя приложения вместе с его URL-адресом и источником значка. И это! Теперь у вас есть новое полнофункциональное приложение для Mac.

Объединитесь, чтобы создать приложение WeChat для Mac

связывать

Создание приложения с веб-сайта

связывать

Узнать больше

Как получить доступ к нескольким мессенджерам одновременно

Скорее всего, WeChat — не единственное приложение, которое вы используете. Даже в Китае у другого приложения для обмена сообщениями, QQ, почти миллиард пользователей. В других частях мира WeChat еще менее актуален перед лицом конкуренции с WhatsApp, Facebook Messenger и Telegram. 

Поэтому, если вы постоянно переключаетесь между несколькими приложениями и получаете всевозможные уведомления, жизнь может стать довольно сложной. Вам не нужно столько стресса. Вместо этого просто используйте специально разработанное решение для объединения всех ваших мессенджеров в один. 

IM+ — лучший в мире агрегатор сообщений. Совместимость с 18 приложениями для чата и другими, включая WeChat, WhatsApp, Facebook Messenger, Skype, Zoom, Slack и Instagram, IM+ объединяет все различные интерфейсы в одном удобном окне приложения, чтобы вам не приходилось переключаться между ними. При этом приложение работает со всеми теми же функциями, ярлыками и файлообменниками. 

Кроме того, вы можете легко разделить свою работу и домашнюю жизнь в приложении IM+, назначив определенные теги, настроив уведомления и настроив обновления статуса. 

Приложение для обмена сообщениями IM+ на Mac

мгновенное сообщение +

Объедините все мессенджеры в одном

мгновенное сообщение +

Узнать больше

Как сделать ваши чаты приватными

С приложением WeChat для Mac, как и с любым другим программным обеспечением, хранящим вашу личную информацию, крайне важно обеспечить конфиденциальность и безопасность ваших разговоров. 

Хотя во время пандемии мы больше не используем компьютеры Mac в общественных местах, когда мы их используем, обычно вокруг не так много людей, что повышает вероятность кражи наших компьютеров, если мы случайно попадем внутрь. одна минута. 

One Switch — это незаменимая утилита для вашего Mac. Это простое приложение находится в строке меню и блокирует экран за считанные секунды. Так просто, как, что. 

Переключатель блокирует клавиатуру и экран

переключатель

Быстрый доступ к функциям macOS

переключатель

Узнать больше

Como você pode ver, o WeChat é o aplicativo de mensagens líder na Ásia e baixar o WeChat para Mac é fácil quando você tem o aplicativo móvel. Melhor ainda, você pode evitar quaisquer restrições em seu local de trabalho fazendo login no WeChat online e criando um novo aplicativo nativo para Mac usando o Unite. Como alternativa, você pode combinar o WeChat com todos os seus outros mensageiros no IM+. E não se esqueça de manter sua privacidade intacta com o One Switch. 

Лучше всего то, что Unite, IM+ и One Switch совершенно бесплатно доступны вам в течение семи дней в рамках пробной версии Setapp — платформы Mac с почти 200 первоклассными приложениями Mac для каждого сценария. Всякий раз, когда вы сталкиваетесь с проблемой, просто откройте Setapp и найдите решение — вы будете поражены тем, как легко можно избежать неэффективности, имея под рукой правильный инструмент. И просматривайте все сопутствующие приложения для iOS в Setapp, чтобы вы могли идти куда угодно, не меняя свой рабочий процесс.

Источник: https://setapp.com

#mac #wechat 

Использование WeChat на Mac для начинающих
Duong Tran

Duong Tran

1678780380

Sử dụng WeChat trên Mac cho người mới bắt đầu

Trong hướng dẫn này, chúng ta tìm hiểu về Cách sử dụng WeChat trên máy Mac. Các ứng dụng nhắn tin là cách mà hầu hết chúng ta giao tiếp ngày nay. Thay vì sử dụng cơ sở hạ tầng viễn thông truyền thống, chúng cho phép đàm thoại qua internet, vì vậy mức độ phổ biến của chúng ngày càng tăng mạnh cùng với sự mở rộng của mạng 3G và LTE. 

Các ứng dụng trò chuyện không chỉ thay thế các cuộc gọi điện thoại và SMS truyền thống mà còn mở rộng triệt để các cách liên lạc, thêm các cuộc gọi video, cuộc gọi hội nghị, nhắn tin nhóm, chia sẻ tệp, hệ thống thanh toán, cập nhật trạng thái, chatbot, v.v. 

Nhìn chung, thị trường nhắn tin ngày càng trở nên bão hòa hơn mỗi ngày. Có Facebook Messenger, WhatsApp, Skype, Telegram, Viber, Snapchat, Instagram, Slack, Signal, Line, v.v. Thông thường, một ứng dụng nhắn tin tức thời sẽ gần như độc quyền trong một thị trường địa lý nhất định. Ví dụ, đối với Trung Quốc, đó là WeChat.

WeChat là gì?

WeChat là một ứng dụng nhắn tin do gã khổng lồ công nghệ Trung Quốc Tencent phát triển vào năm 2011. Đến năm 2018, WeChat được mô tả là ứng dụng độc lập lớn nhất thế giới, với hơn một tỷ người dùng đang hoạt động. Bên cạnh các hiệu ứng mạng, sự phổ biến của ứng dụng có thể là do sự tích hợp chặt chẽ của nó với hầu hết mọi loại giao dịch kinh doanh.

Người dùng WeChat có thể thanh toán hóa đơn, mua hàng hóa và dịch vụ, gửi tiền cho các liên hệ của họ và thậm chí thanh toán tại cửa hàng — tất cả đều thông qua ứng dụng. Vì WeChat hoạt động như một nền tảng nên ngày càng có nhiều nhà cung cấp thêm dịch vụ của họ vào ứng dụng, do đó làm cho nó trở nên hữu ích hơn trong cuộc sống hàng ngày. 

Bạn có thể tải xuống WeChat cho Mac, Windows, iOS, Android và cũng có thể sử dụng trực tuyến. Hãy xem lý do tại sao bạn muốn có ứng dụng WeChat cho Mac và cách sử dụng ứng dụng đó tốt nhất. 

Cách sử dụng ứng dụng WeChat Mac

Trước khi sử dụng Mac WeChat, bạn cần tải xuống phiên bản di động của ứng dụng, vì phiên bản này được sử dụng để xác thực người dùng, tương tự như những gì WhatsApp đang làm. Ứng dụng WeChat có sẵn trên App Store và Google Play.

Sau khi bạn có ứng dụng WeChat dành cho thiết bị di động và tạo tài khoản miễn phí, bạn có thể tải xuống WeChat cho Mac, từ trang web WeChat hoặc qua App Store. Bạn nên chạy OS X 10.11 El Capitan trở lên để khởi chạy ứng dụng. 

Khi mở ứng dụng WeChat dành cho Mac, bạn sẽ thấy lời nhắc mã QR đăng nhập WeChat. Mở WeChat trên điện thoại của bạn, chọn Khám phá trong menu ở dưới cùng rồi Quét mã QR. Trỏ điện thoại của bạn vào mã trên máy Mac và đăng nhập.

Giờ đây, bạn có thể sử dụng WeChat trên máy Mac, điều này giúp bạn không phải liên tục chuyển đổi giữa các thiết bị cũng như chia sẻ tài liệu và tệp dễ dàng hơn. Tuy nhiên, xin lưu ý rằng WeChat dành cho Mac không hỗ trợ cuộc gọi âm thanh và video cũng như Khoảnh khắc. Nhưng bạn vẫn có thể gửi tin nhắn, tệp và video. 

Tải xuống ứng dụng WeChat Mac

Cách sử dụng WeChat trực tuyến

Nếu không hào hứng với việc tải xuống WeChat cho Mac, bạn cũng có thể sử dụng ứng dụng web WeChat. Quá trình xác thực rất giống với Mac: 

Truy cập web.wechat.com

Quét mã QR bằng điện thoại của bạn

Trò chuyện đi! 

quét mã QR ứng dụng trực tuyến WeChatỨng dụng web WeChat hỗ trợ chức năng giống như WeChat trên máy Mac và có thể được truy cập trên bất kỳ máy tính nào, kể cả máy tính công cộng hoặc tại nơi làm việc nếu việc tải xuống của bạn bị hạn chế. Trong một số trường hợp, khi bạn không thể trực tiếp tải xuống WeChat dành cho máy Mac nhưng vẫn muốn sử dụng ứng dụng này trong môi trường gốc, bạn có thể chuyển ứng dụng web sang máy Mac của mình. 

Unite là một công cụ độc đáo để biến hầu hết mọi trang web thành một ứng dụng Mac tiến bộ. Sử dụng công cụ WebKit của Safari, tiện ích này loại bỏ trang web khỏi tất cả các phần mềm của trình duyệt và thêm giao diện và chức năng gốc. Bạn có thể tùy chỉnh giao diện của ứng dụng, bao gồm màu của thanh tiêu đề cũng như biểu tượng trong Dock. 

Để tạo một ứng dụng với Unite, chỉ cần nhập tên của ứng dụng cùng với URL của nó và nguồn của biểu tượng. Thì đấy! Bây giờ bạn có một ứng dụng Mac mới hoạt động đầy đủ.

Đoàn kết tạo ứng dụng WeChat Mac

đoàn kết

Tạo một ứng dụng từ một trang web

đoàn kết

Tìm hiểu thêm

Cách vào nhiều messenger cùng lúc

Rất có thể WeChat không phải là ứng dụng duy nhất bạn sử dụng. Ngay tại Trung Quốc, một ứng dụng nhắn tin khác là QQ cũng có gần một tỷ người dùng. Ở những nơi khác trên thế giới, WeChat thậm chí còn ít liên quan hơn khi phải đối mặt với sự cạnh tranh từ WhatsApp, Facebook Messenger và Telegram. 

Vì vậy, nếu bạn liên tục chuyển đổi giữa nhiều ứng dụng và nhận tất cả các loại thông báo, cuộc sống có thể trở nên khá phức tạp. Bạn không cần tất cả những căng thẳng đó. Thay vào đó, chỉ cần sử dụng một giải pháp được xây dựng riêng để hợp nhất tất cả các trình nhắn tin của bạn thành một. 

IM+ là trình tổng hợp tin nhắn tốt nhất thế giới. Đã hỗ trợ 18 ứng dụng trò chuyện và còn tiếp tục — bao gồm WeChat, WhatsApp, Facebook Messenger, Skype, Zoom, Slack và Instagram — IM+ kết hợp tất cả các giao diện khác nhau trong một cửa sổ ứng dụng tiện lợi để giúp bạn không phải chuyển đổi qua lại liên tục. Đồng thời, ứng dụng hoạt động với tất cả các chức năng, phím tắt và chia sẻ tệp giống nhau. 

Ngoài ra, bạn có thể dễ dàng tách riêng cuộc sống công việc và gia đình của mình trong ứng dụng IM+ bằng cách chỉ định các thẻ cụ thể, tùy chỉnh thông báo và đặt cập nhật trạng thái. 

Ứng dụng nhắn tin IM+ trên máy Mac

nhắn tin nhanh +

Mang tất cả sứ giả vào làm một

nhắn tin nhanh +

Tìm hiểu thêm

Cách giữ cuộc trò chuyện của bạn ở chế độ riêng tư

Với ứng dụng WeChat dành cho Mac, cũng giống như bất kỳ phần mềm nào khác lưu trữ thông tin cá nhân của bạn, việc giữ cho các cuộc hội thoại của bạn riêng tư và an toàn là vô cùng quan trọng. 

Mặc dù trong thời kỳ đại dịch, chúng tôi không sử dụng máy Mac ở nơi công cộng nhiều nữa, nhưng khi chúng tôi sử dụng chúng, có xu hướng không có nhiều người xung quanh, điều này làm tăng khả năng máy tính của chúng tôi bị đánh cắp nếu chúng tôi vô tình bước vào. xa một phút. 

One Switch là tiện ích cuối cùng cho máy Mac của bạn. Ứng dụng đơn giản này nằm trong thanh menu của bạn và khóa màn hình của bạn sau giây lát. Đơn giản như thế. 

One Switch khóa bàn phím và màn hình

một công tắc

Truy cập các tính năng của macOS nhanh chóng

một công tắc

Tìm hiểu thêm

Như bạn có thể thấy, WeChat là ứng dụng nhắn tin hàng đầu ở Châu Á và việc tải xuống WeChat cho Mac thật dễ dàng khi bạn có ứng dụng dành cho thiết bị di động. Tốt hơn nữa, bạn có thể tránh mọi hạn chế tại nơi làm việc của mình bằng cách đăng nhập vào WeChat trực tuyến và tạo một ứng dụng Mac gốc mới từ đó bằng Unite. Ngoài ra, bạn có thể kết hợp WeChat với tất cả các trình nhắn tin khác của mình trong IM+. Và đừng quên giữ nguyên quyền riêng tư của bạn với One Switch. 

Trên hết, Unite, IM+ và One Switch hoàn toàn miễn phí cho bạn trong bảy ngày thông qua bản dùng thử Setapp , một nền tảng Mac với gần 200 ứng dụng Mac được xếp hạng hàng đầu cho mọi trường hợp. Bất cứ khi nào bạn gặp sự cố, chỉ cần mở Setapp và tìm kiếm giải pháp — bạn sẽ ngạc nhiên về số lượng sự thiếu hiệu quả có thể dễ dàng tránh được khi bạn có công cụ phù hợp trong tay. Và hãy xem tất cả các ứng dụng iOS đồng hành trong Setapp, để bạn đi bất cứ đâu mà không cần thay đổi quy trình làm việc của mình.

Nguồn: https://setapp.com

#mac #wechat 

Sử dụng WeChat trên Mac cho người mới bắt đầu
Juanita  Apio

Juanita Apio

1678597560

Using WeChat on Mac for Beginners

In this tutorial we learn about How To Use WeChat On Mac. Messaging apps are the de facto way most of us communicate today. Instead of using the traditional telecom infrastructure, they enable conversations over the internet, so their popularity has been growing sharply with the expansion of 3G and LTE networks. 

Chat apps not just replace the more traditional SMS and phone calls, they radically expand the ways of communication, adding video calls, conference calls, group messaging, file sharing, payment systems, status updates, chatbots, and more. 

By all accounts, the messenger market is getting more and more saturated every day. There’s Facebook Messenger, WhatsApp, Skype, Telegram, Viber, Snapchat, Instagram, Slack, Signal, Line, and lots more. Quite often, an instant messaging app would have a near monopoly in a given geographical market. For China, for example, it’s WeChat.

What Is WeChat?

WeChat is a messenger developed by the Chinese tech giant Tencent in 2011. By 2018, WeChat was described as the largest standalone app in the world, with more than one billion active users. Besides the network effects, the app’s popularity can be attributed to its tight integration with nearly every kind of business transaction.

Users of WeChat can pay bills, purchase goods and services, send money to their contacts, and even pay in stores — all through the app. Since WeChat acts as a platform, more and more vendors are adding their services to the app, thus making it even more useful in daily life. 

You can download WeChat for Mac, Windows, iOS, Android, and also use it online. Let’s see why you’d want to have a WeChat app for Mac and how to use it best. 

How to use WeChat Mac app

Before you use Mac WeChat, you need to download the mobile version of the app, since it’s used for user authentication, similar to what WhatsApp is doing. The WeChat app is available on the App Store and Google Play.

Once you have a mobile WeChat app and create your free account, you can download WeChat for Mac, either from the WeChat website or via App Store. You should run OS X 10.11 El Capitan or later to launch the app. 

When you open the WeChat app for Mac, you’ll see the WeChat login QR code prompt. Open WeChat on your phone, select Discover in the menu at the bottom and then Scan QR Code. Point your phone at the code on your Mac and log in.

Now you can use WeChat on Mac, which makes it easier to not constantly switch between devices as well as share documents and files. Be aware, however, that WeChat for Mac doesn’t support audio and video calls as well as Moments. But you can still send messages, files, and videos. 

WeChat Mac app download

How to use WeChat online

If you’re not excited about the WeChat for Mac download, you can also use the WeChat web app. The authentication process is very similar to the Mac one: 

Visit web.wechat.com

Scan the QR code using your phone

Chat away! 

scan QR code online app WeChatThe WeChat web app supports the same functionality as WeChat on Mac and can be accessed on any computer, including public ones or at work if your downloads are restricted. In some cases, when you can’t download WeChat for Mac directly, but would still like to use it in a native environment, you can port the web app to your Mac. 

Unite is a unique tool for turning nearly any website into a progressive Mac app. Using Safari’s WebKit engine, this utility strips the website of all the browser fluff and adds native appearance and functionality. You can customize the way your app looks, including the title bar color as well as the icon in the Dock. 

To create an app with Unite, simply enter the name of the app with its URL and source the icon. Voila! Now you have a new fully functioning Mac app.

Unite create WeChat app Mac

Unite

Create an app from a website

Unite

Learn more

How to multiple messengers at once

Chances are WeChat is not the only app you use. Even in China, another messaging app QQ has nearly one billion users as well. In other parts of the world, WeChat has even less relevance when facing competition from WhatsApp, Facebook Messenger, and Telegram. 

So if you’re constantly switching between multiple apps and getting all kinds of notifications, life could get quite complicated. You don’t need all that stress. Instead, just use a solution built specifically to merge all your messengers in one. 

IM+ is the world’s best messaging aggregator. Already supporting 18 chat apps and counting — including WeChat, WhatsApp, Facebook Messenger, Skype, Zoom, Slack, and Instagram — IM+ combines all the various interfaces under one convenient app window to free you of constant back-and-forth switching. At the same time, the app works with all the same functionality, shortcuts, and file sharing. 

In addition, you can easily separate your work and home lives within the IM+ app by assigning specific tags, customizing notifications, and setting status updates. 

IM+ app messaging Mac

IM+

Bring all messengers into one

IM+

Learn more

How to keep your conversations private

With WeChat app for Mac, just like with any other software that stores your personal information, keeping your conversations private and secure is of utmost importance. 

Even though, during the pandemic, we don’t use our Macs in public that much anymore, when we do use them, there tends to be not that many people around, which increases the chances of our computers being stolen if we happen to step away for a minute. 

One Switch is the ultimate utility for your Mac. This simple app lives in your menu bar and locks your screen in a second. Simple as that. 

One Switch locks a keyboard and a screen

One Switch

Access macOS features fast

One Switch

Learn more

As you can see, WeChat is a leading messaging app in Asia, and getting a WeChat for Mac download is easy once you have the mobile app. Better yet, you can avoid any restrictions in your workplace by logging into WeChat online and creating a new native Mac app out of it with Unite. Alternatively, you can combine WeChat with all your other messengers in IM+. And don’t forget to keep your privacy intact with One Switch. 

Best of all, Unite, IM+, and One Switch are available to you absolutely free for seven days through a trial of Setapp, a Mac platform with almost 200 top-rated Mac apps for any occasion. Anytime you face a problem, simply open Setapp and look for a solution — you’ll be surprised how many inefficiencies can be easily avoided when you have the right tool at hand. And check out all the companion iOS apps in Setapp as well, so you go anywhere without a single change to your workflow.

Source: https://setapp.com

#mac  #wechat 

Using WeChat on Mac for Beginners

Wechat-chatgpt: Use ChatGPT On Wechat via wechaty

Welcome to wechat-chatgpt 👋

Use ChatGPT On Wechat via wechaty

If you don't have a server or want to experience rapid deployment, you can use Railway to do so, see Usage with Railway.

🌟 Feature

  •  Use ChatGPT On Wechat via wechaty
  •  Support OpenAI Accounts Pool
  •  Support use proxy to login
  •  Add conversation Support
  •  Add Dockerfile
  •  Publish to Docker.hub
  •  Add Railway deploy
  •  Auto Reload OpenAI Accounts Pool
  •  Add sendmessage retry for 429/503

Use with docker in Linux(recommended)

cp config.yaml.example config.yaml
# Change Config.yaml
# run docker command in Linux or WindowsPowerShell
docker run -d --name wechat-chatgpt -v $(pwd)/config.yaml:/app/config.yaml holegots/wechat-chatgpt:latest
# login with qrcode
docker logs -f wechat-chatgpt

Use with docker in Windows

# Create and modify config.yaml in the current directory
# run docker command in WindowsPowerShell
docker run -d --name wechat-chatgpt -v $(pwd)/config.yaml:/app/config.yaml holegots/wechat-chatgpt:latest
# In the Windows command line (cmd) environment, you may mount the current directory like this:
docker run -d --name wechat-chatgpt -v %cd%/config.yaml:/app/config.yaml holegots/wechat-chatgpt:latest
# login with qrcode
docker logs -f wechat-chatgpt

Upgrade docker image version

docker pull holegots/wechat-chatgpt:latest
docker stop wechat-chatgpt
docker rm wechat-chatgpt
# run docker command in Linux or WindowsPowerShell
docker run -d --name wechat-chatgpt -v $(pwd)/config.yaml:/app/config.yaml holegots/wechat-chatgpt:latest
# In the Windows command line (cmd) environment, you may mount the current directory like this:
docker run -d --name wechat-chatgpt -v %cd%/config.yaml:/app/config.yaml holegots/wechat-chatgpt:latest
# login with qrcode
docker logs -f wechat-chatgpt

Install

npm install

NodeJS Version >= 18.0.0

Config

Copy config

You need copy config file for setting up your project.

cp config.yaml.example config.yaml

Get and config Openai account

If you don't have this OpenAI account and you live in China, you can get it here.

Use account and password

You need get OpenAI account and password. Your config.yaml should be like this:

chatGPTAccountPool:
  - email: <your email>
    password: <your password>
# if you hope only some keywords can trigger chatgpt on private chat, you can set it like this:
chatPrivateTiggerKeyword: ""

⚠️ Trigger keywords must appear in the first position of the received message. ⚠️ Pls make sure your network can log in to OpenAI, and if you fail to login in try setting up a proxy or using SessionToken.

Setup proxy:

You can configure in config.yaml:

openAIProxy: <Your Proxy>

CAPTCHAS

The browser portions of this package use Puppeteer to automate as much as possible, including solving all CAPTCHAs. 🔥

Basic Cloudflare CAPTCHAs are handled by default, but if you want to automate the email + password Recaptchas, you'll need to sign up for one of these paid providers:

  • nopecha - Uses AI to solve CAPTCHAS
    • Faster and cheaper
    • Set the NOPECHA_KEY env var to your nopecha API key
    • Demo video of nopecha solving the login Recaptcha (41 seconds)
  • 2captcha - Uses real people to solve CAPTCHAS
    • More well-known solution that's been around longer
    • Set the CAPTCHA_TOKEN env var to your 2captcha API token

So you should config NOPECHA_KEY or CAPTCHA_TOKEN in your Environment Variables.

Start Project

npm run dev

Usage with Railway

Railway is a deployment platform where you can provision infrastructure, develop with that infrastructure locally, and then deploy to the cloud.This section describes how to quickly deploy a wechat-chatgpt project using Railway.

Firstly, you'll need to sign up for a Railway account and sign in using GitHub verification.

Then click the one-click deployment button below to deploy.

Deploy on Railway

After some validation is complete, you can begin the deployment.You will see the following interface:

railway-deployment

Some environment variables need to be configured:

CHAT_GPT_EMAIL : Your OpenAI Account email.

CHAT_GPT_PASSWORD : Your OpenAI Account password.

CHAT_GPT_RETRY_TIMES : The number of times to retry when the OpenAI API returns 429 or 503.

CHAT_PRIVATE_TRIGGER_KEYWORD : If you hope only some keywords can trigger chatgpt on private chat, you can set it.

Click the Deploy button and your service will start deploying shortly.The following interface appears to indicate that the deployment has begun:

railway-deploying

When the deployment is displayed successfully, click to view the logs and find the WeChat login link in Deploy Logs.

railway-deployed

Click to enter and use your prepared WeChat to scan the code to log in.

Log in successfully and start sending and receiving messages(This process can take several minutes):

railway-success

Besides, in deployment, you may encounter the following issues:

  • Error: ⚠️ No chatgpt item in pool : This error means that you have not configured the OpenAI account information correctly. You can solve this problem from the following aspects:1. Check whether the token or openAI account and password are filled in correctly. 2. Redeploy Current Services.Note that the above should be modified on the Variables page in Railway Dashboard. 3. Please make sure that CloudFlare human authentication is present, if it is, Headless browser may not be able to simulate logging into OpenAI.
  • After the deployment is complete, the QR code is not generated.Try refreshing the page to see again if the Deploy Logs panel generated a link and QR code.
  • The generated QR code cannot be scanned.On the generated QR code, there is a link that can be clicked to scan the QR code.
  • Message feedback is very slow.Because Railway's servers are deployed overseas, there is an increase in message feedback latency, but it is still within the acceptance range. If you are time sensitive, you can use your own server deployment.

If you are logging in for the first time, then you need to scan the qrcode.

🤝 Contributing

Contributions, issues and feature requests are welcome!
Feel free to check issues page.

Show your support

Give a ⭐️ if this project helped you!


English | 中文文档

Update Decomber 27, 2022

Using railway & docker deployment, there may be problems that cannot be solved, we are working on it.

Update December 20, 2022

Thanks @transitive-bullshit, The ChatGPT API automates the work.
You should use password & username to login, and config CAPTCHAs.
⚠️ There may be a problem with the Docker image because I don't have an X86 device and Qume doesn't work.


Download Details:

Author: fuergaosi233
Source Code: https://github.com/fuergaosi233/wechat-chatgpt 

#wechat #chatgpt #typescript 

Wechat-chatgpt: Use ChatGPT On Wechat via wechaty
Noelia  Douglas

Noelia Douglas

1672203900

Wechatgpt: Wechat Chatgpt Bot

欢迎使用wechatgpt智能机器人,Let's Chat with ChatGPT

如果觉得不错,请麻烦点个Star,非常感谢。(最新己经添加了docker部署的方式)

仓库地址

https://github.com/houko/wechatgpt

准备运行环境

go mod tidy 
cp config/config.yaml.example local/config.yaml

修改你的token

打开 openai 并注册一个账号, 生成一个api_key并把api_key放到local/config.yaml 的token下,请看如下示例:

chatgpt:
  wechat: 小莫
  token: sk-pKHZD1fLYqXDjjsdsdsdUvIODTT3ssjdfadsJC2gTuqqhTum
  telegram: your telegram token

大陆用户注册openai请参考 注册ChatGPT详细指南

运行App

环境变量

变量名作用
api_key"chatgpt的api_key"必填项
wechat"true" 或缺省如果为true就会启动微信机器人
wechat_keyword"关键字"或缺省如果缺省则发任何消息机器都会回复
telegramtelegram的token或缺省如果要启动tg机器人需要填写
tg_keywordtelegram触发关键字或缺省如果需要关键字触发就填写
tg_whitelisttelegram的触发白名单白名单以外的用户名发消息不会触发
go run main.go

Docker 方式运行wechatgpt

运行微信智能机器人的话运行下面这段代码,微信登陆的地址请查看运行日志docker logs <containerId>

docker run -d \
--name wechatgpt \
-e wechat="true" \
-e wechat_keyword="微信触发关键字" \
xiaomoinfo/wechatgpt:latest

运行微信智能机器人不需要任何触发关键字请运行下面这段代码,适合微信小号专业做机器人用,微信登陆的地址请查看运行日志docker logs <containerId>
警告:以下命令会让任何消息都会被机器人接管,微信主号不要用下面这个命令

docker run -d \
--name wechatgpt \
-e api_key="你的chatgpt api_key" \
-e wechat="true" \
xiaomoinfo/wechatgpt:latest

运行telegram智能机器人的话运行下面这段代码

docker run -d \
--name wechatgpt \
-e api_key="你的chatgpt api_key" \
-e telegram="你的telegram token" \
xiaomoinfo/wechatgpt:latest

如果运行telegram智能机器人时只希望指定的人使用,白名单以外的人发消息机器人不会回复

docker run -d \
--name wechatgpt \
-e api_key="你的chatgpt api_key" \
-e telegram="你的telegram token" \
-e tg_whitelist="username1,username2" \
xiaomoinfo/wechatgpt:latest

如果运行telegram智能机器人时希望在群里回复别人消息,可以指定一个关键字触发

docker run -d \
--name wechatgpt \
-e api_key="你的chatgpt api_key" \
-e telegram="你的telegram token" \
-e tg_keyword="小莫" \
xiaomoinfo/wechatgpt:latest

drawing

微信

ain.go #gosetup
go: downloading github.com/eatmoreapple/openwechat v1.2.1
go: downloading github.com/sirupsen/logrus v1.6.0
go: downloading github.com/spf13/afero v1.9.2
go: downloading github.com/pelletier/go-toml/v2 v2.0.5
go: downloading golang.org/x/sys v0.0.0-20220908164124-27713097b956
/private/var/folders/8t/0nvj_2kn4dl517vhbc4rmb9h0000gn/T/GoLand/___go_build_main_go
访问下面网址扫描二维码登录
https://login.weixin.qq.com/qrcode/QedkOe1I4w==

会自动打开默认浏览器,如果没有打开也可以手动点击上面的链接打开二维码扫微信

2022/12/09 15:15:00 登录成功
2022/12/09 15:15:01 RetCode:0  Selector:2
2022/12/09 15:15:04 RetCode:0  Selector:2
INFO[0099] 0 <Friend:hxh,晓华>                            
INFO[0099] 1 <Friend:刘葵>                                
INFO[0099] 2 <Friend:吕>                                 
INFO[0099] 3 <Friend:wloscar>               

登陆成功后会拉取微信的好友和群组

如何使用

默认为chatgpt,如果想设置其他的触发方式可以修改local/config.yaml的wechat。此时,如果别人给你发消息带有关键字chatgpt ,你的微信就会调用chatGPTAI自动回复你的好友。 当然,在群里也是可以的。

使用场景1

别人给你发消息时,如果消息中带有关键字,系统就会调用AI自动帮你回复此问题。

drawingdrawingdrawing

使用场景2

别人在群里发消息时,如果消息中带有关键字,系统就会调用AI自动帮你回复此问题。

drawingdrawing

使用场景3

自己给自己发消息时,如果消息中带有关键字,系统会也调用AI自动帮你回复此问题。

drawing

意外之喜

drawing

这不比对象来的贴心?

telegram机器人使用方式

方式1: 直接添加小莫的bot进行使用

  • drawing

方式2:自己部署
修改 config下的 chatgpt.telegram的token后运行go run main.go进行启动,参考如下:

chatgpt:
  wechat: 小莫
  token: sk-pKHZD1fLYqXDjjsdsdsdUvIODTT3ssjdfadsJC2gTuqqhTum
  telegram: 5718911250:AAhR1pn52xcCFoM_GyI2g9BaX18S7WbYviQ 

token获取方式,请在telegram中添加好友@botFather并按提示操作

drawing

总结

  • 你可以把它当作你的智能助理,帮助你快速回复消息。
  • 你可以把它当作一个智能机器人,邀请在群里之后通过关键字帮助大家解答问题。
  • 你可以把它当作你的智多星,有什么问题不懂的时候随时问它。

变爸爸事件

放在B站 用chatgpt写了个微信机器人结果变爸爸了

贡献本仓库

如果大家有玩的时候有遇到一些奇怪的对话可以截图发PR分享给大家。另外对本项目有什么想法或者贡献的话欢迎提issuepr

Q&A

1. 返回错误invalid_api_key

这是因为openaiAPI 需要付费,价格非常便宜具体可以官网查看。按照如下参考绑定一下信息卡就可以正常使用了,如果还是有错就把API Key删掉重新建一个。 img.png

2. Cannot load io/fs: malformed module path "io/fs": missing dot in first path element

golang版本太低,需要1.16以上,查看方式为go version

$ go version
go version go1.17.3 linux/amd64

3. 扫码登陆时出现错误 FATA【0023】write token.json: bad file descriptor

删除项目根目录下的token.json后重新扫码登陆即可

4. go mod tidy时connect: connection refused

go: github.com/eatmoreapple/openwechat@v1.2.1: Get https://proxy.golang.org/github.com/eatmoreapple/openwechat/@v/v1.2.1.mod: dial tcp 142.251.43.17:443:

自身网络环境问题,请排查网络设置


Download Details:

Author: houko
Source Code: https://github.com/houko/wechatgpt

License: MIT license

#chatgpt #wechat 

Wechatgpt: Wechat Chatgpt Bot
Noelia  Douglas

Noelia Douglas

1672023420

Wechat Chatgpt: Use ChatGPT on Wechat Via Wechaty

Welcome to wechat-chatgpt 👋

Use ChatGPT On Wechat via wechaty

If you don't have a server or want to experience rapid deployment, you can use Railway to do so, see Usage with Railway.

Update December 20, 2022

Thanks @transitive-bullshit, The ChatGPT API automates the work.
You should use password & username to login, and config CAPTCHAs.
⚠️ There may be a problem with the Docker image because I don't have an X86 device and Qume doesn't work.

Update December 13, 2022

Yesterday (2022.12.12), OpenAI upgraded the authentication measures.

It causes ⚠️ No chatgpt item in pool when you use this project.

However, please rest assured that we are actively looking for an effective solution,

If you have a good solution, feel free to contribute!

🌟 Feature

  •  Use ChatGPT On Wechat via wechaty
  •  Support OpenAI Accounts Pool
  •  Support use proxy to login
  •  Add conversation Support
  •  Add Dockerfile
  •  Publish to Docker.hub
  •  Add Railway deploy
  •  Auto Reload OpenAI Accounts Pool
  •  Add sendmessage retry for 429/503

Use with docker in Linux(recommended)

cp config.yaml.example config.yaml
# Change Config.yaml
# run docker command in Linux or WindowsPowerShell
docker run -d --name wechat-chatgpt -v $(pwd)/config.yaml:/app/config.yaml holegots/wechat-chatgpt:latest
# login with qrcode
docker logs -f wechat-chatgpt

Use with docker in Windows

# Create and modify config.yaml in the current directory
# run docker command in WindowsPowerShell
docker run -d --name wechat-chatgpt -v $(pwd)/config.yaml:/app/config.yaml holegots/wechat-chatgpt:latest
# In the Windows command line (cmd) environment, you may mount the current directory like this:
docker run -d --name wechat-chatgpt -v %cd%/config.yaml:/app/config.yaml holegots/wechat-chatgpt:latest
# login with qrcode
docker logs -f wechat-chatgpt

Upgrade docker image version

docker pull holegots/wechat-chatgpt:latest
docker stop wechat-chatgpt
docker rm wechat-chatgpt
# run docker command in Linux or WindowsPowerShell
docker run -d --name wechat-chatgpt -v $(pwd)/config.yaml:/app/config.yaml holegots/wechat-chatgpt:latest
# In the Windows command line (cmd) environment, you may mount the current directory like this:
docker run -d --name wechat-chatgpt -v %cd%/config.yaml:/app/config.yaml holegots/wechat-chatgpt:latest
# login with qrcode
docker logs -f wechat-chatgpt

Install

npm install && poetry install

Config

Copy config

You need copy config file for setting up your project.

cp config.yaml.example config.yaml

Get and config Openai account

If you don't have this OpenAI account and you live in China, you can get it here.

Use account and password

You need get OpenAI account and password. Your config.yaml should be like this:

chatGPTAccountPool:
  - email: <your email>
    password: <your password>
# if you hope only some keywords can trigger chatgpt on private chat, you can set it like this:
chatPrivateTiggerKeyword: ""

⚠️ Trigger keywords must appear in the first position of the received message. ⚠️ Pls make sure your network can log in to OpenAI, and if you fail to login in try setting up a proxy or using SessionToken.

Setup proxy:

You can configure in config.yaml:

openAIProxy: <Your Proxy>

CAPTCHAS

The browser portions of this package use Puppeteer to automate as much as possible, including solving all CAPTCHAs. 🔥

Basic Cloudflare CAPTCHAs are handled by default, but if you want to automate the email + password Recaptchas, you'll need to sign up for one of these paid providers:

  • nopecha - Uses AI to solve CAPTCHAS
    • Faster and cheaper
    • Set the NOPECHA_KEY env var to your nopecha API key
    • Demo video of nopecha solving the login Recaptcha (41 seconds)
  • 2captcha - Uses real people to solve CAPTCHAS
    • More well-known solution that's been around longer
    • Set the CAPTCHA_TOKEN env var to your 2captcha API token

So you should config NOPECHA_KEY or CAPTCHA_TOKEN in your Environment Variables.

Start Project

npm run dev

If you are logging in for the first time, then you need to scan the qrcode.

Usage with Railway

Railway is a deployment platform where you can provision infrastructure, develop with that infrastructure locally, and then deploy to the cloud.This section describes how to quickly deploy a wechat-chatgpt project using Railway.

Firstly, you'll need to sign up for a Railway account and sign in using GitHub verification.

Then click the one-click deployment button below to deploy.

Deploy on Railway

After some validation is complete, you can begin the deployment.You will see the following interface:

railway-deployment

Some environment variables need to be configured:

CHAT_GPT_EMAIL : Your OpenAI Account email, if you have session_token, It's optional.

CHAT_GPT_PASSWORD : Your OpenAI Account password, if you have session_token, It's optional.

CHAT_GPT_RETRY_TIMES : The number of times to retry when the OpenAI API returns 429 or 503.

CHAT_PRIVATE_TRIGGER_KEYWORD : If you hope only some keywords can trigger chatgpt on private chat, you can set it.

Click the Deploy button and your service will start deploying shortly.The following interface appears to indicate that the deployment has begun:

railway-deploying

When the deployment is displayed successfully, click to view the logs and find the WeChat login link in Deploy Logs.

railway-deployed

Click to enter and use your prepared WeChat to scan the code to log in.

Log in successfully and start sending and receiving messages(This process can take several minutes):

railway-success

Besides, in deployment, you may encounter the following issues:

  • Error: ⚠️ No chatgpt item in pool : This error means that you have not configured the OpenAI account information correctly. You can solve this problem from the following aspects:1. Check whether the token or openAI account and password are filled in correctly. 2. The token may have expired (experience shows that the expiration time of the token is 24 hours), you can go to the chatGPT official website to re-obtain the token. 3. Redeploy Current Services.Note that the above should be modified on the Variables page in Railway Dashboard.
  • After the deployment is complete, the QR code is not generated.Try refreshing the page to see again if the Deploy Logs panel generated a link and QR code.
  • The generated QR code cannot be scanned.On the generated QR code, there is a link that can be clicked to scan the QR code.
  • Message feedback is very slow.Because Railway's servers are deployed overseas, there is an increase in message feedback latency, but it is still within the acceptance range. If you are time sensitive, you can use your own server deployment.

Download Details:

Author: fuergaosi233
Source Code: https://github.com/fuergaosi233/wechat-chatgpt

#chatgpt #wechat 

Wechat Chatgpt: Use ChatGPT on Wechat Via Wechaty

Wechat Login Flutter Plugin

wechat_login

微信登录插件,微信sdk集成,仅实现了登录功能

具体使用查看api文档,有详细注释

android 已通过测试 ios 尚未测试

Use this package as a library

Depend on it

Run this command:

With Flutter:

 $ flutter pub add wechat_login

This will add a line like this to your package's pubspec.yaml (and run an implicit flutter pub get):

dependencies:
  wechat_login: ^0.0.1+2

Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more.

Import it

Now in your Dart code, you can use:

import 'package:wechat_login/wechat_login.dart'; 

Download Details:

Author: 

Source Code: https://pub.dev/packages/wechat_login

#flutter #wechat 

Wechat Login Flutter Plugin

WeChat SDK for Flutter

What's Fluwx

Fluwx is flutter plugin for WeChatSDK which allows developers to call
WeChatSDK native APIs.

Join QQ Group now: 1003811176

Capability

  • Share images, texts, music and so on to WeChat, including session, favorite and timeline.
  • Payment with WeChat.
  • Get auth code before you login in with WeChat.
  • Launch mini program in WeChat.
  • Subscribe Message.
  • Just open WeChat app.
  • Launch app From wechat link.

Preparation

Fluwx is good but not God. You'd better read official documents before integrating Fluwx. Then you'll understand how to generate Android signature, what's universal link for iOS, how to add URL schema for iOS and so on.

Watch Charged Video

Install

Add the following dependencies in your pubspec.yaml file:

Fluwx with pay:

dependencies:
  fluwx: ^${latestVersion}

Fluwx without pay:

dependencies:
  fluwx_no_pay: ^${latestVersion}

NOTE: Never forget to replace ^${latestVersion} with actual version.

Register WxAPI

Register your app via fluwx if necessary.

registerWxApi(appId: "wxd930ea5d5a228f5f",universalLink: "https://your.univerallink.com/link/");

The param universalLink only works with iOS. You can read this document to learn how to create universalLink. You can also learn how to add URL schema, how to add LSApplicationQueriesSchemes in your iOS project. This is essential.

For Android, you shall know to how generate signature for your app in this page. And you have to understand the difference between debug signature and release signature. Once the signature is incorrect, then you'll get errCode = -1.

Capability Document

For more capabilities, you can read the public functions of fluwx.

QA

These questions maybe help

Donate

Buy the writer a cup of coffee。

Subscribe Us On WeChat

Use this package as a library

Depend on it

Run this command:

With Flutter:

 $ flutter pub add fluwx

This will add a line like this to your package's pubspec.yaml (and run an implicit flutter pub get):

dependencies:
  fluwx: ^3.9.2

Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more.

Import it

Now in your Dart code, you can use:

import 'package:fluwx/fluwx.dart'; 

Download Details:

Author: OpenFlutter

Source Code: https://github.com/OpenFlutter/fluwx

#flutter #wechat 

WeChat SDK for Flutter
Royce  Reinger

Royce Reinger

1658503800

Wechat: API, Command and Message Handling for WeChat in Rails

WeChat   

Wechat is a Chinese multi-purpose messaging, social media and mobile payment app developed by Tencent. It was first released in 2011, and by 2018 it was one of the world's largest standalone mobile apps by monthly active users, with over 1 billion monthly active users (902 million daily active users). (According to wiki)

WeChat gem helps Rails developers integrate WeChat Official Accounts Platform or Wechat mini program easily, including features:

  • Sending message API(can be both accessed via console or rails server)
  • Receiving message(rails server is required to be running)
  • Wechat JS-SDK config signature
  • OAuth 2.0 authentication
  • Record session when receiving message from user (Optional)

wechat command shares the same API in console, so you can interact with wechat server quickly without starting up web environment/code.

A responder DSL can be used in Rails controller, which gives an event based interface to handle messages sent by end users.

If Wechat OAuth 2.0 is required by your app, omniauth-wechat-oauth2 is recommended in order to apply devise authentication.

If tencent's weui UI style is adoped in your project, gem weui-rails is available for you.

For web page only wechat application, please use wechat_api, which only contains web features, compared with traditional message type wechat_responder.

There is a more complete wechat-starter demo available, which futher includes the payment SDK feature.

Installation

Use gem install

gem install "wechat"
# If your ruby version < 2.6
# gem install wechat -v 0.12.4

Or add it to your app's Gemfile:

gem 'wechat'
# If your rails version < 6.0
# gem 'wechat', '~> 0.12.4'

Run the following command to install it:

bundle install

Run the generator:

rails generate wechat:install

rails g wechat:install will generate the initial wechat.yml configuration file, including an sample wechat controller and corresponding routes.

Enable session record:

rails g wechat:session
rake db:migrate

Enabling session will generate two files in Rails folder, you can add more columns to wechat_session table and add declaration to link to users table, it's also possible to store data directly in hash_store. If you are using PostgreSQL, using hstore/json maybe better, but the best way is to add a dedicated column to record the data (the Rails way).

Using Redis to store wechat token and ticket:

rails g wechat:redis_store

Redis storage supports Rails application running in multiple servers. It is recommended to use default file storage if there is only one single server. Besides that, wechat command won't read token/ticket stored in Redis.

Enable database wechat configurations:

rails g wechat:config
rake db:migrate

After running the migration, a wechat_configs table will be created that allows storage of multiple wechat accounts.

Configuration

Configure wechat for the first time

Make sure to finish all the setup on rails side first, then submit those setting to Tencent wechat management website. Otherwise, wechat will raise error.

URL address for wechat created by running rails g wechat:install is http://your-server.com/wechat

How to setup appid/corpid and secret see below section.

Configure for command line

To use standalone wechat command, you need to create configuration file ~/.wechat.yml and include content below for public account. The access_token will be written to file /var/tmp/wechat_access_token.

appid: "my_appid"
secret: "my_secret"
access_token: "/var/tmp/wechat_access_token"

For enterprise account, you need to use corpid instead of appid as enterprise account supports multiply application (Tencent calls them agents) in one enterprise account. Obtaining the corpsecret is a little bit tricky, must be created at management mode->privilege setting and create any of management group to obtain. Due to Tencent currently only providing Chinese interface for their management console, it's highly recommended you find a colleague knowing Mandarin to help you to obtain the corpsecret.

Windows users need to store .wechat.yml at C:/Users/[user_name]/ (replace with your user name), also pay attention to the direction of folder separator.

corpid: "my_appid"
corpsecret: "my_secret"
agentid: 1 # Integer, which can be obtained from application settings
access_token: "C:/Users/[user_name]/wechat_access_token"

Configure for Rails

Rails configuration file supports different environment similar to database.yml, after running rails generate wechat:install you can find configuration file at config/wechat.yml

Public account configuration example:

default: &default
  appid: "app_id"
  secret: "app_secret"
  token:  "app_token"
  access_token: "/var/tmp/wechat_access_token"
  jsapi_ticket: "/var/tmp/wechat_jsapi_ticket"

production:
  appid: <%= ENV['WECHAT_APPID'] %>
  secret: <%= ENV['WECHAT_APP_SECRET'] %>
  token:   <%= ENV['WECHAT_TOKEN'] %>
  access_token: <%= ENV['WECHAT_ACCESS_TOKEN'] %>
  jsapi_ticket: <%= ENV['WECHAT_JSAPI_TICKET'] %>
  oauth2_cookie_duration: <%= ENV['WECHAT_OAUTH2_COOKIE_DURATION'] %> # seconds

development:
  <<: *default
  trusted_domain_fullname: "http://your_dev.proxy.qqbrowser.cc"

test:
  <<: *default

Although it's optional for public account, but highly recommended to enable encrypt mode by adding these two items to wechat.yml

default: &default
  encrypt_mode: true
  encoding_aes_key:  "my_encoding_aes_key"

Enterprise account must use encrypt mode (encrypt_mode: true is on by default, no need to configure).

The token and encoding_aes_key can be obtained from management console -> one of the agent application -> Mode selection, select callback mode and get/set.

default: &default
  corpid: "corpid"
  corpsecret: "corpsecret"
  agentid:  1
  access_token: "C:/Users/[user_name]/wechat_access_token"
  token:    ""
  encoding_aes_key:  ""
  jsapi_ticket: "C:/Users/[user_name]/wechat_jsapi_ticket"

production:
  corpid:     <%= ENV['WECHAT_CORPID'] %>
  corpsecret: <%= ENV['WECHAT_CORPSECRET'] %>
  agentid:    <%= ENV['WECHAT_AGENTID'] %>
  access_token:  <%= ENV['WECHAT_ACCESS_TOKEN'] %>
  token:      <%= ENV['WECHAT_TOKEN'] %>
  timeout:    30,
  skip_verify_ssl: true # not recommend
  encoding_aes_key:  <%= ENV['WECHAT_ENCODING_AES_KEY'] %>
  jsapi_ticket: <%= ENV['WECHAT_JSAPI_TICKET'] %>
  oauth2_cookie_duration: <%= ENV['WECHAT_OAUTH2_COOKIE_DURATION'] %>

development:
  <<: *default
  trusted_domain_fullname: "http://your_dev.proxy.qqbrowser.cc"

test:
  <<: *default

 # Multiple Accounts
 #
 # wx2_development:
 #  <<: *default
 #  appid: "my_appid"
 #  secret: "my_secret"
 #  access_token: "tmp/wechat_access_token2"
 #  jsapi_ticket: "tmp/wechat_jsapi_ticket2"
 #
 # wx2_test:
 #  <<: *default
 #  appid: "my_appid"
 #  secret: "my_secret"
 #
 # wx2_production:
 #  <<: *default
 #  appid: "my_appid"
 #  secret: "my_secret"

Notes about supporting multiple accounts of WeChat Official Accounts Platform / WeChat Enterprise (for example, adding account wx2):

Configuration for multiple accounts is similar to multi-database configuration in config/database.yml, where development, test, production segments are the default configuration, one needs to add wx2_development, wx2_test, wx2_production in order to add additional account named wx2.

Declaration of additional wechat_responder:

wechat_responder account: :wx2

Use Wechat.api or Wechat.api(:default) to represent the default wechat api. Use Wechat.api(:wx2) to call for wechat api of account wx2.

When using Wechat command line, one can switch to another wechat account by adding optional parameters -a ACCOUNT [--account=ACCOUNT].

For details about supporting multiple accounts, please check PR 150

For wechat mini program, can specified by the item type:

# Mini Program Accounts

  mini_development:
    <<: *default
    appid: "my_appid"
    secret: "my_secret"
    # `mp` is short for **mini program**
    type: 'mp'

Database wechat account configuration

After enabling database account configuration, the following table will be created:

AttributeTypeAnnotation
environmentstringRequired. Environment of account configuration. Typical values are: production, development and test. For example, a production config will only be available in production. Default to development.
accountstringRequired. Custom wechat account name. Account names must be unique within each environment.
enabledbooleanRequired. Whether this configuration is activated. Default to true.
appidstringPublic account id. Either this attribute or corpid must be specified.
secretstringPublic account configuration. Required when appid exists.
corpidstringCorp account id. Either this attribute or appid must be specified.
corpsecretstringCorp account configuration. Required when corpid exists.
agentidintegerCorp account configuration. Required when corpid exists.
encrypt_modeboolean 
encoding_aes_keystringRequired when encrypt_mode is true.
tokenstringRequired.
access_tokenstringRequired. Path to access token storage file.
jsapi_ticketstringRequired. Path to jsapi ticket storage file.
skip_verify_sslboolean 
timeoutintegerDefault to 20.
trusted_domain_fullnamestring 

After updating database account configurations, you need to restart the server, or call Wechat.reload_config! to reload the updates.

Configure priority

Running wechat command in the root folder of Rails application will be using the Rails configuration first (default section), if can not find it, will relay on ~\.wechat.yml, such behavior enables managing more wechat public account and enterprise account without changing your home ~\.wechat.yml file.

When database account configuration is enabled, database configurations will be loaded after yml configuration file or environment parameters. When configurations with the same account name exist in both database and yml file or environment parameter, the one in the database will take precedence.

Wechat server timeout setting

Stability varies for Tencent wechat server, so setting a long timeout may be needed, default is 20 seconds if not set.

Skip the SSL verification

SSL Certification can also be corrupted for some reason in China, it's reported and if it happens to you, you can set skip_verify_ssl: true. (not recommend)

Configure individual responder with different appid

Sometimes, you may want to host more than one enterprise/public wechat account in one Rails application, so you can provide this configuration info when calling wechat_responder or wechat_api

class WechatFirstController < ActionController::Base
   wechat_responder account: :new_account, account_from_request: Proc.new{ |request| request.params[:wechat] }

   on :text, with:"help", respond: "help content"
end

Or you can provide full list of options.

class WechatFirstController < ActionController::Base
   wechat_responder appid: "app1", secret: "secret1", token: "token1", access_token: Rails.root.join("tmp/access_token1"),
                    account_from_request: Proc.new{ |request| request.params[:wechat] }

   on :text, with:"help", respond: "help content"
end

account_from_request is a Proc that takes in request as its parameter, and returns the corresponding wechat account name. In the above examples, controller will choose the account based on the wechat parameter passed in the request. If account_from_request is not specified, or this Proc evaluates to nil, configuration specified by account or the full list of options will be used.

JS-SDK helper

JS-SDK gives you control over Wechat App behavior in html, by injecting a config signature, helper wechat_config_js does that in a simple way:

To make wechat_config_js work, you need to put wechat_api or wechat_responder at controller first.

<body>
<%= wechat_config_js debug: false, api: %w(hideMenuItems closeWindow) -%>
<script type="application/javascript">
  wx.ready(function() {
      wx.hideOptionMenu();
  });
</script>
<a href="javascript:wx.closeWindow();">Close</a>
</body>

Configure the trusted_domain_fullname if you are in development mode and app is running behind a reverse proxy server, otherwise wechat gem won't be able to get the correct url to be signed later.

OAuth2.0 authentication

For public account, code below will get following user's info.

class CartController < ActionController::Base
  wechat_api
  def index
    wechat_oauth2 do |openid|
      @current_user = User.find_by(wechat_openid: openid)
      @articles = @current_user.articles
    end

    # specify account_name to use arbitrary wechat account configuration
    # wechat_oauth2('snsapi_base', nil, account_name) do |openid|
    #  ...
    # end
  end
end

For enterprise account, code below will get enterprise member's userinfo.

class WechatsController < ActionController::Base
  layout 'wechat'
  wechat_responder
  def apply_new
    wechat_oauth2 do |userid|
      @current_user = User.find_by(wechat_userid: userid)
      @apply = Apply.new
      @apply.user_id = @current_user.id
    end
  end
end

wechat_oauth2 already implements the necessary OAuth2.0 and cookie logic. userid defined as the enterprise member UserID. openid defined as the user who following the public account, also notice openid will be different for the same user for different following public accounts.

Notice:

  • If you use wechat_responder in your controller, you cannot use create and show action in your controller, otherwise it will throw errors.
  • If you get redirect_uri parameter error message, make sure you set the correct callback url value in wechat management console with path Development center / Webpage service / Webpage authorization for retrieving user basic information.

The API privilege

wechat gems won't handle any privilege exceptions. (except token timeout, but it's not important to you as it's auto retry/recovery in gems internally), but Tencent will control a lot of privilege based on your public account type and certification, for more info please reference official document.

Command line mode

The available API is different between public account and enterprise account, so wechat gems provide different set of command.

Feel safe if you can not read Chinese in the comments, it's kept there in order to copy & find in the official documentation easier.

Public account command line

$ wechat
Wechat Public Account commands:
  wechat addvoicetorecofortext [VOICE_ID]                       # AI 开放接口 - 提交语音
  wechat callbackip                                             # 获取微信服务器 IP 地址
  wechat clear_quota                                            # 接口调用次数清零
  wechat custom_image [OPENID, IMAGE_PATH]                      # 发送图片客服消息
  wechat custom_music [OPENID, THUMBNAIL_PATH, MUSIC_URL]       # 发送音乐客服消息
  wechat custom_news [OPENID, NEWS_YAML_PATH]                   # 发送图文客服消息
  wechat custom_text [OPENID, TEXT_MESSAGE]                     # 发送文字客服消息
  wechat custom_video [OPENID, VIDEO_PATH]                      # 发送视频客服消息
  wechat custom_voice [OPENID, VOICE_PATH]                      # 发送语音客服消息
  wechat customservice_getonlinekflist                          # 获取在线客服接待信息
  wechat group_create [GROUP_NAME]                              # 创建分组
  wechat group_delete [GROUP_ID]                                # 删除分组
  wechat group_update [GROUP_ID, NEW_GROUP_NAME]                # 修改分组名
  wechat groups                                                 # 查询所有分组
  wechat material_get [MEDIA_ID, PATH]                          # 永久媒体下载
  wechat material_add [MEDIA_TYPE, PATH]                        # 永久媒体上传
  wechat material_add_news [MPNEWS_YAML_PATH]                   # 永久图文素材上传
  wechat material_count                                         # 获取永久素材总数
  wechat material_delete [MEDIA_ID]                             # 删除永久素材
  wechat material_list [TYPE, OFFSET, COUNT]                    # 获取永久素材列表
  wechat media [MEDIA_ID, PATH]                                 # 媒体下载
  wechat media_hq [MEDIA_ID, PATH]                              # 高清音频下载
  wechat media_create [MEDIA_TYPE, PATH]                        # 媒体上传
  wechat media_uploadimg [IMAGE_PATH]                           # 上传图文消息内的图片
  wechat media_uploadnews [MPNEWS_YAML_PATH]                    # 上传图文消息素材
  wechat menu                                                   # 当前菜单
  wechat menu_addconditional [CONDITIONAL_MENU_YAML_PATH]       # 创建个性化菜单
  wechat menu_create [MENU_YAML_PATH]                           # 创建菜单
  wechat menu_delconditional [MENU_ID]                          # 删除个性化菜单
  wechat menu_delete                                            # 删除菜单
  wechat menu_trymatch [USER_ID]                                # 测试个性化菜单匹配结果
  wechat message_mass_delete [MSG_ID]                           # 删除群发消息
  wechat message_mass_get [MSG_ID]                              # 查询群发消息发送状态
  wechat message_mass_preview [WX_NAME, MPNEWS_MEDIA_ID]        # 预览图文消息素材
  wechat qrcode_create_limit_scene [SCENE_ID_OR_STR]            # 请求永久二维码
  wechat qrcode_create_scene [SCENE_ID_OR_STR, EXPIRE_SECONDS]  # 请求临时二维码
  wechat qrcode_download [TICKET, QR_CODE_PIC_PATH]             # 通过 ticket 下载二维码
  wechat queryrecoresultfortext [VOICE_ID]                      # AI 开放接口 - 获取语音识别结果
  wechat shorturl [LONG_URL]                                    # 长链接转短链接
  wechat tag [TAGID]                                            # 获取标签下粉丝列表
  wechat tag_add_user [TAG_ID, OPEN_IDS]                        # 批量为用户打标签
  wechat tag_create [TAGNAME, TAG_ID]                           # 创建标签
  wechat tag_del_user [TAG_ID, OPEN_IDS]                        # 批量为用户取消标签
  wechat tag_delete [TAG_ID]                                    # 删除标签
  wechat tag_update [TAG_ID, TAGNAME]                           # 更新标签名字
  wechat tags                                                   # 获取所有标签
  wechat template_message [OPENID, TEMPLATE_YAML_PATH]          # 模板消息接口
  wechat translatecontent [CONTENT]                             # AI 开放接口 - 微信翻译
  wechat user [OPEN_ID]                                         # 获取用户基本信息
  wechat user_batchget [OPEN_ID_LIST]                           # 批量获取用户基本信息
  wechat user_change_group [OPEN_ID, TO_GROUP_ID]               # 移动用户分组
  wechat user_group [OPEN_ID]                                   # 查询用户所在分组
  wechat user_update_remark [OPEN_ID, REMARK]                   # 设置备注名
  wechat users                                                  # 关注者列表
  wechat wxa_msg_sec_check [CONTENT]                            # 检查一段文本是否含有违法违规内容。
  wechat wxacode_download [WXA_CODE_PIC_PATH, PATH, WIDTH]      # 下载小程序码
  wechat clear_quota                                            # 接口调用次数清零

Enterprise account command line

$ wechat
Wechat Enterprise Account commands:
  wechat agent [AGENT_ID]                                  # 获取企业号应用详情
  wechat agent_list                                        # 获取应用概况列表
  wechat batch_job_result [JOB_ID]                         # 获取异步任务结果
  wechat batch_replaceparty [BATCH_PARTY_CSV_MEDIA_ID]     # 全量覆盖部门
  wechat batch_replaceuser [BATCH_USER_CSV_MEDIA_ID]       # 全量覆盖成员
  wechat batch_syncuser [SYNC_USER_CSV_MEDIA_ID]           # 增量更新成员
  wechat callbackip                                        # 获取微信服务器 IP 地址
  wechat clear_quota                                       # 接口调用次数清零
  wechat convert_to_openid [USER_ID]                       # userid 转换成 openid
  wechat convert_to_userid [OPENID]                        # openid 转换成 userid
  wechat custom_image [OPENID, IMAGE_PATH]                 # 发送图片客服消息
  wechat custom_music [OPENID, THUMBNAIL_PATH, MUSIC_URL]  # 发送音乐客服消息
  wechat custom_news [OPENID, NEWS_YAML_PATH]              # 发送图文客服消息
  wechat custom_text [OPENID, TEXT_MESSAGE]                # 发送文字客服消息
  wechat custom_video [OPENID, VIDEO_PATH]                 # 发送视频客服消息
  wechat custom_voice [OPENID, VOICE_PATH]                 # 发送语音客服消息
  wechat department [DEPARTMENT_ID]                        # 获取部门列表
  wechat department_create [NAME, PARENT_ID]               # 创建部门
  wechat department_delete [DEPARTMENT_ID]                 # 删除部门
  wechat department_update [DEPARTMENT_ID, NAME]           # 更新部门
  wechat getusercumulate [BEGIN_DATE, END_DATE]            # 获取累计用户数据
  wechat getusersummary [BEGIN_DATE, END_DATE]             # 获取用户增减数据
  wechat invite_user [USER_ID]                             # 邀请成员关注
  wechat material [MEDIA_ID, PATH]                         # 永久媒体下载
  wechat material_add [MEDIA_TYPE, PATH]                   # 永久媒体上传
  wechat material_count                                    # 获取永久素材总数
  wechat material_delete [MEDIA_ID]                        # 删除永久素材
  wechat material_list [TYPE, OFFSET, COUNT]               # 获取永久素材列表
  wechat media [MEDIA_ID, PATH]                            # 媒体下载
  wechat media_create [MEDIA_TYPE, PATH]                   # 媒体上传
  wechat media_hq [MEDIA_ID, PATH]                         # 高清音频媒体下载
  wechat media_uploadimg [IMAGE_PATH]                      # 上传图文消息内的图片
  wechat menu                                              # 当前菜单
  wechat menu_addconditional [CONDITIONAL_MENU_YAML_PATH]  # 创建个性化菜单
  wechat menu_create [MENU_YAML_PATH]                      # 创建菜单
  wechat menu_delconditional [MENU_ID]                     # 删除个性化菜单
  wechat menu_delete                                       # 删除菜单
  wechat menu_trymatch [USER_ID]                           # 测试个性化菜单匹配结果
  wechat message_send [OPENID, TEXT_MESSAGE]               # 发送文字消息
  wechat qrcode_download [TICKET, QR_CODE_PIC_PATH]        # 通过 ticket 下载二维码
  wechat tag [TAG_ID]                                      # 获取标签成员
  wechat tag_add_department [TAG_ID, PARTY_IDS]            # 增加标签部门
  wechat tag_add_user [TAG_ID, USER_IDS]                   # 增加标签成员
  wechat tag_create [TAGNAME, TAG_ID]                      # 创建标签
  wechat tag_del_department [TAG_ID, PARTY_IDS]            # 删除标签部门
  wechat tag_del_user [TAG_ID, USER_IDS]                   # 删除标签成员
  wechat tag_delete [TAG_ID]                               # 删除标签
  wechat tag_update [TAG_ID, TAGNAME]                      # 更新标签名字
  wechat tags                                              # 获取所有标签
  wechat template_message [OPENID, TEMPLATE_YAML_PATH]     # 模板消息接口
  wechat upload_replaceparty [BATCH_PARTY_CSV_PATH]        # 上传文件方式全量覆盖部门
  wechat upload_replaceuser [BATCH_USER_CSV_PATH]          # 上传文件方式全量覆盖成员
  wechat user [OPEN_ID]                                    # 获取用户基本信息
  wechat user_batchdelete [USER_ID_LIST]                   # 批量删除成员
  wechat user_create [USER_ID, NAME]                       # 创建成员
  wechat user_delete [USER_ID]                             # 删除成员
  wechat user_list [DEPARTMENT_ID]                         # 获取部门成员详情
  wechat user_simplelist [DEPARTMENT_ID]                   # 获取部门成员
  wechat user_update_remark [OPEN_ID, REMARK]              # 设置备注名

Note: replaceparty full departments uploads only supports a single root node as a department and does not support parallel multiple root nodes.

Command line usage demo (partially)

Fetch all users open id

$ wechat users

{"total"=>4, "count"=>4, "data"=>{"openid"=>["oCfEht9***********", "oCfEhtwqa***********", "oCfEht9oMCqGo***********", "oCfEht_81H5o2***********"]}, "next_openid"=>"oCfEht_81H5o2***********"}

Fetch user info

$ wechat user "oCfEht9***********"

{"subscribe"=>1, "openid"=>"oCfEht9***********", "nickname"=>"Nickname", "sex"=>1, "language"=>"zh_CN", "city"=>"徐汇", "province"=>"上海", "country"=>"中国", "headimgurl"=>"http://wx.qlogo.cn/mmopen/ajNVdqHZLLBd0SG8NjV3UpXZuiaGGPDcaKHebTKiaTyof*********/0", "subscribe_time"=>1395715239}

Fetch menu

$ wechat menu

{"menu"=>{"button"=>[{"type"=>"view", "name"=>"保护的", "url"=>"http://***/protected", "sub_button"=>[]}, {"type"=>"view", "name"=>"公开的", "url"=>"http://***", "sub_button"=>[]}]}}

Menu create

Running command rails g wechat:menu to generate a menu definition yaml file:

button:
 -
  name: "Want"
  sub_button:
   -
    type: "scancode_waitmsg"
    name: "绑定用餐二维码"
    key: "BINDING_QR_CODE"
   -
    type: "click"
    name: "预订午餐"
    key:  "BOOK_LUNCH"
   -
    type: "miniprogram"
    name: "小程序示例"
    url:  "http://ericguo.com/"
    appid: "wx1234567890"
    pagepath: "pages/index"
 -
  name: "Query"
  sub_button:
   -
    type: "click"
    name: "进出记录"
    key:  "BADGE_IN_OUT"
   -
    type: "click"
    name: "年假余额"
    key:  "ANNUAL_LEAVE"
 -
  type: "view"
  name: "About"
  url:  "http://blog.cloud-mes.com/"

Running command below to upload the menu:

$ wechat menu_create menu.yaml

Caution: make sure you have management privilege for this application, otherwise you will get 60011 error.

Send custom news

Sending custom_news should also be defined as a yaml file, like articles.yml

articles:
 -
  title: "习近平在布鲁日欧洲学院演讲"
  description: "新华网比利时布鲁日 4 月 1 日电 国家主席习近平 1 日在比利时布鲁日欧洲学院发表重要演讲"
  url: "http://news.sina.com.cn/c/2014-04-01/232629843387.shtml"
  pic_url: "http://i3.sinaimg.cn/dy/c/2014-04-01/1396366518_bYays1.jpg"

After that, you can run this command:

$ wechat custom_news oCfEht9oM*********** articles.yml

Send template message

Sending template message via yaml file is similar, too, define template.yml and content is just the template content.

template:
  template_id: "o64KQ62_xxxxxxxxxxxxxxx-Qz-MlNcRKteq8"
  url: "http://weixin.qq.com/download"
  topcolor: "#FF0000"
  data:
    first:
      value: "Hello, you successfully registered"
      color: "#0A0A0A"
    keynote1:
      value: "5km Health Running"
      color: "#CCCCCC"
    keynote2:
      value: "2014-09-16"
      color: "#CCCCCC"
    keynote3:
      value: "Centry Park, Pudong, Shanghai"
      color: "#CCCCCC"
    remark:
      value: "Welcome back"
      color: "#173177"

After that, you can run this command:

$ wechat template_message oCfEht9oM*********** template.yml

In code:

template = YAML.load(File.read(template_yaml_path))
Wechat.api.template_message_send Wechat::Message.to(openid).template(template["template"])

If using wechat_api or wechat_responder in controller, can also use wechat as shortcut (supports multi account):

template = YAML.load(File.read(template_yaml_path))
wechat.template_message_send Wechat::Message.to(openid).template(template["template"])

wechat_api - Rails Controller Wechat API

Although user can always access all wechat features via Wechat.api, but it's highly recommended to use wechat directly in the controller. It's not only mandatory required if you plan to support multi-account, it also helps to separate the wechat specific logic from the model layer.

class WechatReportsController < ApplicationController
  wechat_api
  layout 'wechat'

  def index
    @lots = Lot.with_preloading.wip_lot
  end
end

Using wechat api at ActiveJob/Rake tasks

Using Wechat.api to access the wechat api function at any place.

Below is an example via rails console to call AI Voice Recognition API:

# Audio file with ID3 version 2.4.0, contains:MPEG ADTS, layer III, v2,  40 kbps, 16 kHz, Monaural
test_voice_file='test_voice.mp3'
Wechat.api.addvoicetorecofortext('test_voice_id', File.open(test_voice_file))
Wechat.api.queryrecoresultfortext 'test_voice_id'

Checking the signature

Using Wechat.decrypt(encrypted_data,session_key, iv) to decode the data. via. Signature Checking

wechat_responder - Rails Responder Controller DSL

In order to respond to the message user sent, Rails developer needs to create a wechat responder controller and define the routing in routes.rb

  resource :wechat, only: [:show, :create]

So the ActionController should be defined like below:

class WechatsController < ActionController::Base
  wechat_responder

  # default text responder when no other match
  on :text do |request, content|
    request.reply.text "echo: #{content}" # Just echo
  end

  # When receive 'help', will trigger this responder
  on :text, with: 'help' do |request|
    request.reply.text 'help content'
  end

  # When receive '<n>news', will match and will get count as <n> as parameter
  on :text, with: /^(\d+) news$/ do |request, count|
    # Wechat article can only contain max 8 items, large than 8 will be dropped.
    news = (1..count.to_i).each_with_object([]) { |n, memo| memo << { title: 'News title', content: "No. #{n} news content" } }
    request.reply.news(news) do |article, n, index| # article is return object
      article.item title: "#{index} #{n[:title]}", description: n[:content], pic_url: 'http://www.baidu.com/img/bdlogo.gif', url: 'http://www.baidu.com/'
    end
  end

  on :event, with: 'subscribe' do |request|
    request.reply.text "#{request[:FromUserName]} subscribe now"
  end

  # When unsubscribe user scan qrcode qrscene_xxxxxx to subscribe in public account
  # notice user will subscribe public account at the same time, so wechat won't trigger subscribe event anymore
  on :scan, with: 'qrscene_xxxxxx' do |request, ticket|
    request.reply.text "Unsubscribe user #{request[:FromUserName]} Ticket #{ticket}"
  end

  # When subscribe user scan scene_id in public account
  on :scan, with: 'scene_id' do |request, ticket|
    request.reply.text "Subscribe user #{request[:FromUserName]} Ticket #{ticket}"
  end

  # When no any on :scan responder can match subscribe user scanned scene_id
  on :event, with: 'scan' do |request|
    if request[:EventKey].present?
      request.reply.text "event scan got EventKey #{request[:EventKey]} Ticket #{request[:Ticket]}"
    end
  end

  # When enterprise user press menu BINDING_QR_CODE and success to scan bar code
  on :scan, with: 'BINDING_QR_CODE' do |request, scan_result, scan_type|
    request.reply.text "User #{request[:FromUserName]} ScanResult #{scan_result} ScanType #{scan_type}"
  end

  # Except QR code, wechat can also scan CODE_39 bar code in enterprise account
  on :scan, with: 'BINDING_BARCODE' do |message, scan_result|
    if scan_result.start_with? 'CODE_39,'
      message.reply.text "User: #{message[:FromUserName]} scan barcode, result is #{scan_result.split(',')[1]}"
    end
  end

  # When user clicks the menu button
  on :click, with: 'BOOK_LUNCH' do |request, key|
    request.reply.text "User: #{request[:FromUserName]} click #{key}"
  end

  # When user views URL in the menu button
  on :view, with: 'http://wechat.somewhere.com/view_url' do |request, view|
    request.reply.text "#{request[:FromUserName]} view #{view}"
  end

  # When user sends an image
  on :image do |request|
    request.reply.image(request[:MediaId]) # Echo the sent image to user
  end

  # When user sends a voice
  on :voice do |request|
    # Echo the sent voice to user
    # request.reply.voice(request[:MediaId])

    voice_id = request[:MediaId]
    # It's only avaiable for Service Account and enable it in dashboard.
    recognition = request[:Recognition]
    request.reply.text "#{voice_id} #{recognition}"
  end

  # When user sends a video
  on :video do |request|
    nickname = wechat.user(request[:FromUserName])['nickname'] # Call wechat api to get sender nickname
    request.reply.video(request[:MediaId], title: 'Echo', description: "Got #{nickname} sent video") # Echo the sent video to user
  end

  # When user sends location message with label
  on :label_location do |request|
    request.reply.text("Label: #{request[:Label]} Location_X: #{request[:Location_X]} Location_Y: #{request[:Location_Y]} Scale: #{request[:Scale]}")
  end

  # When user sends location
  on :location do |request|
    request.reply.text("Latitude: #{request[:Latitude]} Longitude: #{request[:Longitude]} Precision: #{request[:Precision]}")
  end

  on :event, with: 'unsubscribe' do |request|
    request.reply.success # user can not receive this message
  end

  # When user enters the app / agent app
  on :event, with: 'enter_agent' do |request|
    request.reply.text "#{request[:FromUserName]} enter agent app now"
  end

  # When batch job "create/update user (incremental)" is finished.
  on :batch_job, with: 'sync_user' do |request, batch_job|
    request.reply.text "sync_user job #{batch_job[:JobId]} finished, return code #{batch_job[:ErrCode]}, return message #{batch_job[:ErrMsg]}"
  end

  # When batch job "replace user (full sync)" is finished.
  on :batch_job, with: 'replace_user' do |request, batch_job|
    request.reply.text "replace_user job #{batch_job[:JobId]} finished, return code #{batch_job[:ErrCode]}, return message #{batch_job[:ErrMsg]}"
  end

  # When batch job "invite user" is finished.
  on :batch_job, with: 'invite_user' do |request, batch_job|
    request.reply.text "invite_user job #{batch_job[:JobId]} finished, return code #{batch_job[:ErrCode]}, return message #{batch_job[:ErrMsg]}"
  end

  # When batch job "replace department (full sync)" is finished.
  on :batch_job, with: 'replace_party' do |request, batch_job|
    request.reply.text "replace_party job #{batch_job[:JobId]} finished, return code #{batch_job[:ErrCode]}, return message #{batch_job[:ErrMsg]}"
  end

  # mass sent job finish result notification
  on :event, with: 'masssendjobfinish' do |request|
    # https://mp.weixin.qq.com/wiki?action=doc&id=mp1481187827_i0l21&t=0.03571905015619936#8
    request.reply.success # request is XML result hash.
  end

  # The customer agrees to call back the chat content archive event
  on :change_external_contact do |request|
    # https://open.work.weixin.qq.com/api/doc/90000/90135/92005
    request.reply.success # request is XML result hash.
  end

  # Session event callback
  on :msgaudit_notify do |request|
    # https://open.work.weixin.qq.com/api/doc/90000/90135/95039
    request.reply.success # request is XML result hash.
  end

  # If no match above will fallback to below
  on :fallback, respond: 'fallback message'
end

So the important statement is only wechat_responder, all other is just a DSL:

on <message_type> do |message|
 message.reply.text "some text"
end

The block code will be running to respond to user's message.

Below are currently supported message_types:

  • :text text message, using :with to match text content like on(:text, with:'help'){|message, content| ...}
  • :image image message
  • :voice voice message
  • :shortvideo shortvideo message
  • :video video message
  • :label_location location message with label
  • :link link message
  • :event event message, using :with to match particular event, supports regular expression match similar to text message.
  • :click virtual event message, wechat still sends event message,but gems will map to menu click event.
  • :view virtual view message, wechat still sends event message,but gems will map to menu view page event.
  • :scan virtual scan message, wechat still sends event message, but gems will map to scan event.
  • :batch_job virtual batch job message
  • :location virtual location message
  • :fallback default message, when no other responder can handle incoming message, will be used as a fallback handler

Transfer to customer service

class WechatsController < ActionController::Base
  # When no other responder can handle incoming message, will transfer to human customer service.
  on :fallback do |message|
    message.reply.transfer_customer_service
  end
end

Caution: do not set default text responder if you want to use multiply human customer service, other will lead text message can not transfer.

Notifications

Example:

ActiveSupport::Notifications.subscribe('wechat.responder.after_create') do |name, started, finished, unique_id, data|
  WechatLog.create request: data[:request], response: data[:response]
end

Known Issues

  • Sometimes, enterprise account can not receive the menu message due to Tencent server unable to resolve DNS, so using IP as a callback URL is more stable, but it never happens for user sent text messages.
  • Enterprise batch "replace users" uses a CSV format file, but if you are using the downloaded template directly, it's not working, must open the CSV file in Excel first, then save as CSV format again, seems Tencent only supports Excel "Save as CSV" file format.
  • If you using unicorn behind nginx and https, you need to set trusted_domain_fullname and point it to https, otherwise it will be http and will lead to invalid signature in the JS-SDK.

中文文档 Chinese document

Author: Eric-Guo
Source Code: https://github.com/Eric-Guo/wechat 
License: MIT license

#ruby #wechat #sdk #framework 

Wechat: API, Command and Message Handling for WeChat in Rails
Jamel  O'Reilly

Jamel O'Reilly

1657152840

WCDB: A Cross-Platform Database Framework Developed By WeChat

WCDB

WCDB is an efficient, complete, easy-to-use mobile database framework used in the WeChat application. It's currently available on iOS, macOS and Android.

WCDB for iOS/macOS

Features

Easy-to-use. Through WCDB, you can get objects from database in one line code.

WINQ (WCDB language integrated query): WINQ is a native data querying capability which frees developers from writing glue code to concatenate SQL query strings.

ORM (Object Relational Mapping): WCDB provides a flexible, easy-to-use ORM for creating tables, indices and constraints, as well as CRUD through ObjC objects.

[database getObjectsOfClass:WCTSampleConvenient.class
                  fromTable:tableName
                      where:WCTSampleConvenient.intValue>=10
                      limit:20];

Efficient. Through the framework layer and sqlcipher source optimization, WCDB have more efficient performance.

  • Multi-threaded concurrency: WCDB supports concurrent read-read and read-write access via connection pooling.
  • Batch Write Performance Test. For more benchmark data, please refer to our benchmark.

Complete.

  • Encryption Support: WCDB supports database encryption via SQLCipher.
  • Corruption recovery: WCDB provides a built-in repair kit for database corruption recovery.
  • Anti-injection: WCDB provides a built-in protection from SQL injection.

Getting Started

Prerequisites

  • Apps using WCDB can target: iOS 7 or later, macOS 10.9 or later.
  • Xcode 8.0 or later required.
  • Objective-C++ required.

Installation

  • Via Cocoapods:
    1. Install CocoaPods.
    2. Run pod repo update to make CocoaPods aware of the latest available WCDB versions.
    3. In your Podfile, add pod 'WCDB' to your app target.
    4. From the command line, run pod install.
    5. Use the .xcworkspace file generated by CocoaPods to work on your project.
    6. Add #import <WCDB/WCDB.h> at the top of your Objective-C++ source files and start your WCDB journey.
    7. Since WCDB is an Objective-C++ framework, for those files in your project that includes WCDB, you should rename their extension .m to .mm.
  • Via Carthage:
    1. Install Carthage.
    2. Add github "Tencent/WCDB" to your Cartfile.
    3. Run carthage update.
    4. Drag WCDB.framework from the appropriate platform directory in Carthage/Build/ to the Linked Binary and Libraries section of your Xcode project’s Build Phases settings.
    5. On your application targets' Build Phases settings tab, click the "+" icon and choose New Run Script Phase. Create a Run Script with carthage copy-frameworks and add the paths to the frameworks under Input Files: $(SRCROOT)/Carthage/Build/iOS/WCDB.framework or $(SRCROOT)/Carthage/Build/Mac/WCDB.framework.
    6. Add #import <WCDB/WCDB.h> at the top of your Objective-C++ source files and start your WCDB journey.
    7. Since WCDB is an Objective-C++ framework, for those files in your project that includes WCDB, you should rename their extension .m to .mm.
  • Via Dynamic Framework: Note that Dynamic frameworks are not compatible with iOS 7. See “Static Framework” for iOS 7 support.
    1. Getting source code from git repository and update the submodule of sqlcipher.
      • git clone https://github.com/Tencent/wcdb.git
      • cd wcdb
      • git submodule update --init sqlcipher
    2. Drag WCDB.xcodeproj in wcdb/apple/ into your project.
    3. Add WCDB.framework to the Enbedded Binaries section of your Xcode project's General settings. Note that there are two frameworks here and the dynamic one should be chosen. You can check it at Build Phases->Target Dependencies. The right one is WCDB while `WCDB iOS Static is used for static lib.
    4. Add #import <WCDB/WCDB.h> at the top of your Objective-C++ source files and start your WCDB journey.
    5. Since WCDB is an Objective-C++ framework, for those files in your project that includes WCDB, you should rename their extension .m to .mm.
  • Via Static Framework:
    1. Getting source code from git repository and update the submodule of sqlcipher.
      • git clone https://github.com/Tencent/wcdb.git
      • cd wcdb
      • git submodule update --init sqlcipher
    2. Drag WCDB.xcodeproj in wcdb/apple/ into your project.
    3. Add WCDB iOS Static to the Target Dependencies section of your Xcode project's Build Phases settings.
    4. Add WCDB.frameworklibz.tbd to the Linked Binary and Libraries section of your Xcode project's Build Phases settings. Note that there are two WCDB.framework, you should choose the one from WCDB iOS Static target.
    5. Add -all_load and -ObjC to the Other Linker Flags section of your Xcode project's Build Settings.
    6. Add #import <WCDB/WCDB.h> at the top of your Objective-C++ source files and start your WCDB journey.
    7. Since WCDB is an Objective-C++ framework, for those files in your project that includes WCDB, you should rename their extension .m to .mm.

Tutorials

Tutorials can be found here.

Documentations

  • Documentations can be found on our Wiki.
  • API references for iOS/macOS can be found here.
  • Performance data can be found on our benchmark.

WCDB for Android

Features

  • Database encryption via SQLCipher.
  • ORM/persistence solution via Room from Android Architecture Components.
  • Concurrent access via connection pooling from modern Android framework.
  • Repair toolkit for database corruption recovery.
  • Database backup and recovery utility optimized for small backup size.
  • Log redirection and various tracing facilities.
  • API 14 (Android 4.0) and above are supported.

Getting Started

To include WCDB to your project, choose either way: import via Maven or via AAR package.

Import via Maven

To import WCDB via Maven repositories, add the following lines to build.gradle on your app module:

dependencies {
    compile 'com.tencent.wcdb:wcdb-android:1.0.8'
    // Replace "1.0.8" to any available version.
}

This will cause Gradle to download AAR package from JCenter while building your application.

If you want to use Room persistence library, you need to add the Google Maven repository to build.gradle to your root project.

allprojects {
    repositories {
        jcenter()
        google()    // Add this line
    }
}

Also add dependencies to module build.gradle.

dependencies {
    compile 'com.tencent.wcdb:room:1.0.8'
    // Replace "1.0.8" to any available version.

    annotationProcessor 'android.arch.persistence.room:compiler:1.1.1'
    // Don't forget to include Room annotation compiler from Google.
}

Import Prebuilt AAR Package

  1. Download AAR package from release page.   2. Import the AAR as new module. In Android Studio, select File -> New -> New Module... menu and choose "Import JAR/AAR Package".   3. Add a dependency on the new module. This can be done using File -> Project Structure... in Android Studio, or by adding following code to application's build.gradle:

dependencies {
    // Change "wcdb" to the actual module name specified in step 2.
    compile project(':wcdb')
}

Migrate from Plain-text SQLite Databases

WCDB has interfaces very similar to Android SQLite Database APIs. To migrate you application from AOSP API, change import path from android.database.* to com.tencent.wcdb.*, and android.database.sqlite.* to com.tencent.wcdb.database.*. After import path update, your application links to WCDB instead of AOSP API.

To open or create an encrypted database, use with-password versions of SQLiteDatabase.openOrCreateDatabase(), SQLiteOpenHelper.getWritableDatabase(), or Context.openOrCreateDatabase().

Note: WCDB uses byte[] for password instead of String in SQLCipher Android Binding.

String password = "MyPassword";
SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase("/path/to/database", password.getBytes(), 
        null, null);

See sample-encryptdb for sample for transferring data between plain-text and encrypted databases.

Use WCDB with Room

To use WCDB with Room library, follow the Room instructions. The only code to change is specifying WCDBOpenHelperFactory when getting instance of the database.

SQLiteCipherSpec cipherSpec = new SQLiteCipherSpec()
        .setPageSize(4096)
        .setKDFIteration(64000);

WCDBOpenHelperFactory factory = new WCDBOpenHelperFactory()
        .passphrase("passphrase".getBytes())  // passphrase to the database, remove this line for plain-text
        .cipherSpec(cipherSpec)               // cipher to use, remove for default settings
        .writeAheadLoggingEnabled(true)       // enable WAL mode, remove if not needed
        .asyncCheckpointEnabled(true);        // enable asynchronous checkpoint, remove if not needed

AppDatabase db = Room.databaseBuilder(this, AppDatabase.class, "app-db")
                .allowMainThreadQueries()
                .openHelperFactory(factory)   // specify WCDBOpenHelperFactory when opening database
                .build();

See sample-persistence for samples using Room library with WCDB. See sample-room-with-a-view for samples using Room library with WCDB and other architecture components from Google.

sample-room-with-a-view comes from Google's CodeLabs with modification of just a few rows. Search for [WCDB] keyword for the modification.

See here for the original tutorial.

Corruption Recovery

See sample-repairdb for instructions how to recover corrupted databases using RepairKit.

Redirect Log Output

By default, WCDB prints its log message to system logcat. You may want to change this behavior in order to, for example, save logs for troubleshooting. WCDB can redirect all of its log outputs to user-defined routine using Log.setLogger(LogCallback) method.

Build from Sources

Build WCDB Android with Prebuilt Dependencies

WCDB itself can be built apart from its dependencies using Gradle or Android Studio. To build WCDB Android library, run Gradle on android directory:

$ cd android
$ ./gradlew build

Building WCDB requires Android NDK installed. If Gradle failed to find your SDK and/or NDK, you may need to create a file named local.properties on the android directory with content:

sdk.dir=path/to/sdk
ndk.dir=path/to/ndk

Android Studio will do this for you when the project is imported.

Build Dependencies from Sources

WCDB depends on OpenSSL crypto library and SQLCipher. You can rebuild all dependencies if you wish. In this case, a working C compiler on the host system, Perl 5, Tcl and a bash environment is needed to be installed on your system.

To build dependencies, checkout all submodules, set ANDROID_NDK_ROOT environment variable to your NDK path, then run build-depends-android.sh:

$ export ANDROID_NDK_ROOT=/path/to/ndk
$ ./build-depends-android.sh

This will build OpenSSL crypto library and generate SQLCipher amalgamation sources and place them to proper locations suitable for WCDB library building.

Author: Tencent
Source Code: https://github.com/Tencent/wcdb
License: View license

#ios #swift #wechat 

WCDB: A Cross-Platform Database Framework Developed By WeChat
Luna  Mosciski

Luna Mosciski

1595939340

How Nebula Graph Stores a One Trillion Connections Social Network

WeChat is one of the social network apps in the world that deals with large scale heterogeneous graphs. The dataset to be processed has:

  • One trillion edges/connections
  • A total dataset of 150TB
  • An hourly update of 100 billion connections,

And it is a huge challenge. The team at WeChat encountered problems when using Nebula Graph, an open source distributed graph database.

However, through deep customization capabilities in the database, the team has realized some useful on-demand features. They include big data storage, data import for large data sets with a fast performance, version control, rollback at the second level, and access to the database at millisecond level.

The Challenges Facing Large Internet Companies

Most well-known graph databases are not capable of dealing with truly big data. For example, the community version of Neo4j provides single-host service and is widely adopted in the knowledge graph area. However, when it comes to a very large data set this solution misses the mark. And large data sets are increasingly common in today’s business world.

Plus, there are issues like data consistency and disaster recovery to consider if you choose a multi-copy implementation. Janus Graph has solved the big data storage problem by using external metadata management, kv storage and indexes. Yet the performance has been widely criticized. As a result, most graph database solutions that the WeChat team evaluated are many times better than Janus Graph in terms of performance.

Some Internet companies build their own databases. These self-developed solutions are catering to their own business requirements, rather than for general graph scenarios. So, they support only a limited proportion of query syntaxes.

GeaBase From Ant Financial

GeaBase is another option, mainly used in the finance industry. It features a self-developed query language, pushdown computation and millisecond latency. The main scenarios for its usage include risk management in financial organizations. To this end, it supports a transaction network with trillions of edges/relationships, storing real-time transaction data, real-time fraud detection.

It is also useful for recommendation engines. This includes applications like stocks and securities recommendations. Its Ant Forest features the capability to store trillions of nodes, strong data consistency, and low latency querying. It also has a GNN feature for Dynamic Graph CNN, for online inference based on dynamic graphs.

iGraph From Alibaba

There is also iGraph, a graph indexing and query system. It stores user behavior information and serves as one of the four backbone middle platforms in Alibaba. iGraph has adopted Gremlin as its graph query language for real-time queries of e-commerce relationships.

ByteGraph From ByteDance (a.k.a TikTok)

By adding a cache layer to the kv layer, ByteGraph splits the relationships into B+ trees for efficient access to edges and data sampling. The structure is like the TAO of Facebook.

Architecture of the WeChat Big Data Solution

The WeChat team has come up with the following architecture to solve the big data storage and processing problem.

Why Nebula Graph?

As seen in the architecture above, a graph database is the main component of the solution. WeChat ended up selecting Nebula Graph as the starting point of its journey in exploring graph databases.

WeChat found Nebula Graph had the most potential for handling huge dataset storage needs based on the capability of dataset partitioning and an independent relationship storage. It also had pushdown computation and MPP optimization based on the strong consistency storage engine. Finally, the team had extensive experience in the graph database field and a proven model for abstraction for big data.

Problems in Practice Nebula Graph

Insufficient Memory

The WeChat team encountered memory issues. At its essence, it was a problem of performance versus resources. Memory occupation is an un-neglectable issue in an application dealing with large scale datasets. There are a couple of components in RocksDB that contribute to memory usage. There are Block cache, Indexes and bloom filters. There are also Memtables and Blocks pinned by iterators. So, the WeChat team moved to optimize memory utilization. It began with block cache optimization. To do this, it adopted a global LRU cache to control the cache occupation of all RocksDB instances in a machine.

Then the team did a bloom filter optimization. An edge is designed as a key-value pair and stored in RocksDB. If all keys are stored in a bloom filter and each key occupies 10bit, then the memory required by the entire filter will exceed the machine memory by a large margin.

The team observed that most of the time the requests are to acquire a list of edges for a specific node. Therefore, the team adopted a prefix bloom filter. Another optimization was made to create indexes for properties on vertices, which enables acceleration for most requests. Finally, the memory occupation of a single-host filter is at the gigabyte level without sacrificing the speed of most requests.

#database #graph database #case study #use cases #wechat #nebula graph

How Nebula Graph Stores a One Trillion Connections Social Network