Python Telegram Bot + 3rd Party Listener - python

I'm working with Python Telegram Bot https://python-telegram-bot.readthedocs.io/
I'm trying to implement a bot function into a 3rd party listener, so when the handle_event() is fired, with a telegram username as parameter, the bot bans that member from the group. here we go with an example:
def handle_event(event):
result = offerCancelled_event.processReceipt(receipt)
#Double check if we got a result
if(result):
#Set telegram user
telegram_user = "Ulvur"
users.remove(telegram_user)
file = open('users.txt', 'w+')
for user in users:
file.write('%s\n' % user)
file.close()
if(telegram_user not in users):
Update.effective_chat.ban_member(telegram_user)
Following code is returning AttributeError: 'property' object has no attribute 'ban_member' when function is fired.

Update is a class and the property Update.effective_chat can only be properly evaluated for instances of that class. If you want to make simple calls to the Bot API, you should instantiate an instance of the telegram.Bot class and call its methods - in your case Bot.ban_chat_member. Please see the Introduction to the API for a more detailed explanation of how to use the API methods.

Related

Python, Deep Link directing User to Bot Private Chat after Button click

I have a question that I can‘t resolve it. I am using Telebot API to create a Telegram Bot, all I want to do is, when Bot sends a Button in a Group, when User clicks this Button first time, to be redirected in the Bots Private Message "http://telegram.me/<Bot_Username>?start=start", where User can Start the Bot.
My code in Python:
#bot.callback_query_handler(func=lambda call: 'begin_config' in call.data)
def query(call):
bot.message.reply_to(text="http://telegram.me/<BotName>?start=start")
#bot.message_handler(commands=['bot_config'])
def bot_config(message):
text_to_post = "Greetings, Bot here, hit the Button to configure"
markup = telebot.types.InlineKeyboardMarkup()
markup.add(telebot.types.InlineKeyboardButton(text='Bot configuration', callback_data='begin_config'))
bot.reply_to(message, text_to_reply, reply_markup=markup)
I am getting the Error: AttributeError: 'TeleBot' object has no attribute 'message'
When I use
call.message.reply_markup(text="http://telegram.me/?start=start")
I am getting the Error: AttributeError: TypeError: 'InlineKeyboardMarkup' object is not callable
I just want User, when he clicks the Button [Bot configuration] first time to get the Private Chat of the Bot, where the User can start the Bot.
enter image description here
Thank's for anyone attempting to solve my Problem, but I solved it by myself. It was unclear for me since Bot can't send Private Messages to Users, as long as they have not Start-ed the Bot. So I wanted to redirect the User to Start my Bot, by clicking the Button posted by the Bot in the Group.
In this case the Callback is not needed at all, just create a Button containing the Bots Address as Url and send it to ChatID, when User clicks the Button, it automatically invites the User to Start the Bot, after that User can Start the Bot and can get Private Messages.
markup = telebot.types.InlineKeyboardMarkup()
markup.add(telebot.types.InlineKeyboardButton(text='Bot configuration',
url="https://t.me/<Bot_Name>"))
bot.send_message(chat_id=chat_id, caption=text_to_post,
reply_markup=markup, parse_mode=ParseMode.HTML)

SlackClient Python RTM not capturing messages

I want to write a simple slack bot, which responds a given string to # mentions, however I am not able to make the official documentation code to work.
I gave all OAuth permission to the bot and have the following code:
from slack import RTMClient
#RTMClient.run_on(event="message")
def gravity_bot(**payload):
data = payload['data']
print(data.get('text'))
try:
rtm_client = RTMClient(
token="my_token_auth_code",
connect_method='rtm.start'
)
print("Bot is up and running!")
rtm_client.start()
except Exception as err:
print(err)
I think the connection is established, as the "Bot is up and running" message appears, however on the slack channel to bot seems to be offline, also I am not able to get any response in the terminal, not for direct messages, not for channel messages even after inviting the bot to given channels.
Sorry couldn't let this one go.. I figured it out and here are the steps:
Create a "Classic" app in Slack (this is the only way to get the appropriate scopes), just click this link: https://api.slack.com/apps?new_classic_app=1
From the "Add features and functionality" tab click on "bots":
Click the "Add Legacy Bot User" button (this will add the "rtm.stream" scope that you need, but that you cannot add manually)
From the basic information page, install your app in a workspace
From the OAuth & Permissions page, copy the "Bot User OAuth Access Token" (the bottom one)
Run the following code (slightly modified version of the code in the docs)
from slack_sdk.rtm import RTMClient
# This event runs when the connection is established and shows some connection info
#RTMClient.run_on(event="open")
def show_start(**payload):
print(payload)
#RTMClient.run_on(event="message")
def say_hello(**payload):
print(payload)
data = payload['data']
web_client = payload['web_client']
if 'Hello' in data['text']:
channel_id = data['channel']
thread_ts = data['ts']
user = data['user']
web_client.chat_postMessage(
channel=channel_id,
text=f"Hi <#{user}>!",
thread_ts=thread_ts
)
if __name__ == "__main__":
slack_token = "<YOUR TOKEN HERE>"
rtm_client = RTMClient(token=slack_token)
rtm_client.start()
Previous answer:
Hmm, this is tricky one... According to the docs this only works for "classic" Slack apps, so that might be the first pointer. It explicitly says that you should not upgrade your app. Furthermore, you'll need to set the right permissions (god knows which ones) by selecting the "bot" scope.
Honestly, I haven't been able to get this running. Looks like Slack is getting rid of this connection method, so you might have more luck looking into the "Events API". I know it's not the ideal solution because its not as real-time, but it looks better documented and it will stay around for a while. Another approach could be polling. Its not sexy but it works...
My guess is that your problem is that there is not a valid connection, but there is no proper error handling in the Slack library. The message is printed before you actually connect, so that doesn't indicate anything.

Python Telegram Bot - How to update the text of the last message my bot has sent

I'm using python-telegram-bot (python-telegram-bot.org) to communicate with Telegram from Python3
I would like to update the last reply I sent.
Currently, the code below sends the message and then sends
another message 5 seconds later.
def echo(bot, update):
update.message.reply_text("Sorry, you're on your own, kiddo.")
time.sleep(5)
update.message.reply_text("Seriously, you're on your own, kiddo.")
I'd like to update the last message instead.
I tried
bot.editMessageText("Seriously, you're on your own, kiddo.",
chat_id=update.message.chat_id,
message_id=update.message.message_id)
which works in the examples to update replace an inline keyboard with a a message, but that crashes (and does not update the last message I sent as a bot).
I believe the order of your arguments in edit_message_text() is wrong. Check out the docs for that:
def echo(bot, update):
# Any send_* methods return the sent message object
msg = update.message.reply_text("Sorry, you're on your own, kiddo.")
time.sleep(5)
# you can explicitly enter the details
bot.edit_message_text(chat_id=update.message.chat_id,
message_id=msg.message_id,
text="Seriously, you're on your own, kiddo.")
# or use the shortcut (which pre-enters the chat_id and message_id behind)
msg.edit_text("Seriously, you're on your own, kiddo.")
The docs for the shortcut message.edit_text() is here.

Receiving service messages in a group chat using Telegram Bot

I am trying to create a bot in my group to help me track the group users who have invited other users into the group.
I have disabled the privacy mode so the bot can receive all messages in a group chat. However, it seems to be that update.message only gets messages supplied by other users but not service messages like Alice has added Bob into the group
Is there any way that I can get these service messages as well?
Thanks for helping!
I suppose you are using python-telegram-bot library.
You can add a handler with a specific filter to listen to service messages:
from telegram.ext import MessageHandler, Filters
def callback_func(bot, update):
# here you receive a list of new members (User Objects) in a single service message
new_members = update.message.new_chat_members
# do your stuff here:
for member in new_members:
print(member.username)
def main():
...
dispatcher.add_handler(MessageHandler(Filters.status_update.new_chat_members, callback_func)
There are several more service message types your bot may receive using the Filters module, check them out here.

How to use python-slackclient RTM using multiple token (bot-user)

Hi I have an issue integrating slack custom bot-user into my slack app, based on python-slackclient documentation python-slackclient
to use the RTM
import time
from slackclient import SlackClient
token = "xoxp-xxxxxxxxx"# found at https://api.slack.com/web#authentication
sc = SlackClient(token)
if sc.rtm_connect():
while True:
print sc.rtm_read()
time.sleep(1)
else:
print "Connection Failed, invalid token?"
that code is working for bot-user token, but since I use oauth, I need to connect RTM using the bot_access_token everytime user install my app to act on behalf my app to the added team
any solution or example how to do it?
Cheers,
Your question is had to understand. You wrote:
since I use oauth, I need to connect RTM using the bot_access_token everytime user install my app to act on behalf my app to the added team
The access token you're using here...
token = "xoxp-xxxxxxxxx"# found at https://api.slack.com/web#authentication
...should be the same as the access token that is associated with your bot. (You should not make your bot use your own personal access token!) You can get an access token for your bot at https://my.slack.com/services/new/bot (assuming you're logged into Slack in the browser with which you follow that link).
If you participate in multiple Slack "teams" (a Slack "team" being basically a company), you'll need to set up a separate bot for each "team". Each bot will have a different access token. To pass the correct access token in to your bot, you could add a command-line parameter, or read the token from an environment variable, or read it from disk, among other options.
You can loop over tokens for connecting if you are planning to setup bot
for multiple teams, then your code can be converted to :-
clients = [SlackClient(token) for t in tokens]
for client in clients:
client.rtm_connect()
while True:
for client in clients:
print client.rtm_read()
time.sleep(1)

Categories