How to get caption from Telegramm message(Pyrogram) - python

I'm newbie at Python. I want to parse certain dialog(contains only captions to pics) with Pyrogram. But if i use iter_history() methog it returns none if message contains pic+text.Like that.
import asyncio
from pyrogram import Client
app = Client("my_acc")
target = "dialog_example" # "me" refers to your own chat (Saved Messages)
with app:
for message in app.iter_history(target):
print(message.text)
None
Process finished with exit code 0

message.text is a message's text. If you want the caption of a message (or document rather), access message.caption.

Related

How read slack channel messages using python-slackclient

I want to get messages from my slack channel "general", may be with parameter like retrieve last 50 Messages.
I checked documents, there are all stuff like sending message, listing channels, leaving channels, finding channel ID's etc. But I didn't found anything which can help me to get channel's messages "once" using that channel ID.
Is this function available in python-slackclient. Or any workaround?
You are looking for the conversations.history method, which pulls the last 100 message events of a conversation. The sample code is pretty straightforward:
import os
# Import WebClient from Python SDK (github.com/slackapi/python-slack-sdk)
from slack_sdk import WebClient
from slack_sdk.errors import SlackApiError
# WebClient insantiates a client that can call API methods
# When using Bolt, you can use either `app.client` or the `client` passed to listeners.
client = WebClient(token=os.environ.get("SLACK_BOT_TOKEN"))
# Store conversation history
conversation_history = []
# ID of the channel you want to send the message to
channel_id = "C12345"
try:
# Call the conversations.history method using the WebClient
# conversations.history returns the first 100 messages by default
# These results are paginated, see: https://api.slack.com/methods/conversations.history$pagination
result = client.conversations_history(channel=channel_id)
conversation_history = result["messages"]
# Print results
logger.info("{} messages found in {}".format(len(conversation_history), id))
except SlackApiError as e:
logger.error("Error creating conversation: {}".format(e))
After getting Channel ID's you can use api_calls to retrieve messages like this
history = client.api_call(api_method='conversations.history',data={'channel':'CHANNEL_ID_HERE'})
print(history)

Discord API messaging when another function returns a value

I am using python discord API https://discordpy.readthedocs.io/en/latest/api.html and I would like to have a forever loop(like a while loop) That checks with function whether on the site is a new content(I have already wrote a scraper). In other words: if scraper sees a new post it will return a value(link). I want to connect it with discord and when there is an output of that function, it will be sent to the text channel. I have completely no clue how to do that. The scraper function is asynchronous. All that comes to my mind is to make a second thread and log in and then message manually through selenium
Use webhooks.
Create a webhook then whenever your scraper gets new data, submit a POST request to the webhook url you created with the content parameter set to your data.
Example:
import requests
WEBHOOK_URL = "https://discordapp.com/api/webhooks/123456789/qWerRYtyuqwfq" # Example webhook url
def sendToDiscord(webhookUrl, data):
return requests.post(webhookUrl, json={'content': data})
data = myScraper.get_data() # Whenever there is data from your scraper
sendToDiscord(WEBHOOK_URL, data) # Send it to Discord
Note: You can format your message, add images etc... by using the appropriate params

import string from different file in python

Last week I installed the Telegram application on my Raspberry Pi and set up a script to send me notifications on time (with crontab). But as I have to enter a Token from my Bot and a chat_id of my Telegram Account I want to store them one time in different files so I only have to change it in one file if they ever change. So far my code looks like this:
telepot.py:
import telepot
import values
with open("values.py", "r") as valuesFile:
chat_id, Token = valuesFile.readlines()
bot = telepot.Bot('TOKEN')
bot.sendMessage(chat_id, 'message')
values.py:
chat_id = 'ChatID'
Token = 'TOKEN'
But I haven't figured out how to get the information from my other files. I have looked on the internet but I'm not really good a programming like at all so I hoped somebody could help me with finding the right command to import the two strings from my files and use them as the declaration for chat_id and TOKEN.
Your question is rather unclear. Are you importing the values and tokens from a python file? A text file?. I will guide you through a few examples.
If you want to import the values from another python file (let's call it values.py and let's assume it's in the same directory as the script you sent (telepot.py))
values.py
chat_id = 'YOUR_CHAT_ID'
TOKEN = 'YOUR_TOKEN'
telepot.py
import values
import telepot
bot = telepot.Bot(values.TOKEN)
Now, let's assume the values you need are in a text file, values.txt that looks like:
TOKEN
CHAT_ID
telepot.txt
import telepot
with open("values.txt", "r") as valuesFile:
chatId, Token = valuesFile.readlines()
bot = telepot.Bot(Token)
bot.sendMessage(chatId, "This is a message")

How to work with slackbot in python?

I am trying to build a slackbot for my group , I tried sample codes and some other things but its not sending message to the group.
first i tried via terminal
export SLACK_API_TOKEN="my_token_id"
Then
from slackclient import SlackClient
import os
slack_token = os.environ["SLACK_API_TOKEN"]
sc = SlackClient(slack_token)
sc.api_call(
"chat.postMessage",
channel="#random",
text="Hello from Python! :tada:",
thread_ts="283.5127(dummy_id)",
reply_broadcast=False
)
print(sc)
#<slackclient.client.SlackClient object at 0x109b77ba8>
But there is no message in slack group.
I tried with this code:
from slackclient import SlackClient
import os
slack_token = os.environ['SLACK_API_TOKEN']
sc = SlackClient(slack_token)
print(sc.api_call("channels.list"))
its retuning :
{'error': 'invalid_auth', 'ok': False}
I am not getting what i am doing wrong , Access token is correct , i want to post some messages via a bot , so how i can create a bot on slack and using that bot i can send messages via python ?
I had similar issues when I implemented a slack bot with php & symfony.
It's not that simple to create and configure the slack app, bot and OAuth permissions properly.
I explained all these configurations in this blog post if you need it: https://blog.eleven-labs.com/en/en/replace-erp-by-slack-bot-with-dialogflow-and-symfony/
Also my code in PHP is very similar to what you need to parse Slack requests and post to its API.
Summary, TL;DR:
Go to https://api.slack.com/apps and click on 'Create New App'.
In this app configuration, go to the left menu 'Bot Users' or from 'Basic Information' > 'Add features and functionality' > 'Bots'.
Still in this app config, go to the menu 'OAuth & Permissions' and allow the scope 'chat:write:bot' and copy the value of 'OAuth Access Token'
From your code, call 'chat.postMessage' API method with an 'Authorization' header using previous token value.
built this from some examples found on the web: liza daly - brobot : github.com
and
How to Build Your First Slack Bot with Python : fullstackpython.com
certainly not the best implementation but it functions as an appropriate answer to (i think)
import random
import time
import re
from slackclient import SlackClient
bot_id = None
slack_token = 'xoxb-no.more.mister.nice.gui'
sc = SlackClient(slack_token)
# constants
RTM_READ_DELAY = 1 # 1 second delay between reading from RTM
DEFAULT_RESPONSE = "greetings: 'hello', 'hi', 'greetings', 'sup', 'what's up' / commands: 'do'"
DEFAULT_COMMAND = "do"
MENTION_REGEX = "^<#(|[WU].+?)>(.*)"
def parse_bot_commands(slack_events):
"""
parses a list of events coming from the slack rtm api to find bot commands
:param slack_events:
:return:
"""
for event in slack_events:
if event["type"] == "message" and not "subtype" in event:
user_id, message = parse_direct_mention(event["text"])
if user_id == bot_id:
return message, event["channel"]
return None, None
def parse_direct_mention(message_text):
"""
finds direct message and returns user id
:param message_text:
:return:
"""
matches = re.search(MENTION_REGEX, message_text)
# the first group contains the user name, the second group contains
# the remaining message
return (matches.group(1), matches.group(2).strip()) if matches else (None, None)
def handle_command(command, channel):
"""
executes bot command if the command is known
:param command:
:param channel:
:return:
"""
GREETING_KEYWORDS = ("hello", "hi", "greetings", "sup", "what's up",)
GREETING_RESPONSES = ["'sup brah", "hey", "*headnod*", "didjageddathingahsencha?"]
# default response is help text for the user
default_response = "Not sure what you mean. Try *{}*.".format(DEFAULT_RESPONSE)
# finds and executes the given command, filling the response
response = None
#implement more commands below this line
if command in GREETING_KEYWORDS:
response = random.choice(GREETING_RESPONSES)
else:
if command.startswith(DEFAULT_COMMAND):
response = "Sure...write some more code and I'll do that"
# Sends the response back to the channel
sc.api_call(
"chat.postMessage",
channel="#the_danger_room",
as_user="true:",
text=response or default_response)
if __name__ == "__main__":
if sc.rtm_connect(with_team_state=False):
print("Connected and running!")
#call web api method auth.test to get bot usre id
bot_id = sc.api_call("auth.test")["user_id"]
while True:
command, channel = parse_bot_commands(sc.rtm_read())
if command:
handle_command(command, channel)
time.sleep(RTM_READ_DELAY)
else:
print("Connection failed. Exception traceback printed above.")

How can I send a message to a group conversation with Skype4Py in Python

I've been trying to get my script to send a message to a group conversation in Skype using the Skype4Py library, the only way I am currently able to send messages is to specific users.
import Skype4Py
Skype = Skype4Py.Skype()
Skype.Attach()
Skype.SendMessage('namehere','testmessage')
Does anyone know how I can change my code to send a message to a group conversation?
The following little script should work. (Assuming you already have a group chat open)
def sendGroupChatMessage():
"""
Send Group Chat Messages.
"""
import Skype4Py as skype
skypeClient = skype.Skype()
skypeClient.Attach()
for elem in skypeClient.ActiveChats:
if len(elem.Members) > 2:
elem.SendMessage("SomeMessageHere")
I'm basically importing all the current chats, checking the number of members and sending a message accordingly. It should be easy to check within various groups too.
To get the handles too, change your function to this.
def sendGroupChatMessage():
"""
Send Group Chat Messages.
"""
import Skype4Py as skype
skypeClient = skype.Skype()
skypeClient.Attach()
for elem in skypeClient.ActiveChats:
if len(elem.Members) > 2:
for friend in elem.Members:
print friend.Handle
elem.SendMessage("SomeMessageHere")
If you can bookmark your chat, you just have to do this, then.
>>> groupTopic = 'Insert a Topic Here'
>>> for chat in skypeClient.BookmarkedChats:
if chat.Topic == groupTopic:
chat.SendMessage("Send a Message Here")
This is the final code that should be standalone.
def sendGroupChatMessage(topic=""):
"""
Send Group Chat Messages.
"""
import Skype4Py as skype
skypeClient = skype.Skype()
skypeClient.Attach()
messageSent = False
for elem in skypeClient.ActiveChats:
if len(elem._GetMembers()) > 2 and elem.Topic == topic:
elem.SendMessage("SomeMessageHere")
messageSent = True
if not messageSent:
for chat in skypeClient.BookmarkedChats:
if chat.Topic == topic:
chat.SendMessage("SomeMessageHere")
messageSent = True
return messageSent

Categories