I've been trying to use outgoing webhook in Slack to export messages from the channel to my Python program but I can't find the way to do it, so I wonder if even a thing like this exists?
Slack seems to have an API you can use to retreive the messages of a given channel.
Follow this link : https://api.slack.com/messaging/retrieving
You can make a GET request to retreive the full history of the given conversation (so all the messages) :
GET https://slack.com/api/conversations.history?token=YOUR_TOKEN_HERE&channel=CONVERSATION_ID_HERE
Content-type: application/json
You can easily make GET requests wiht python using the library called 'requests'.
If you're able to have a valid API token and the ID of the conversation, you will then be able to get all the messages of the chosen conversation.
Related
I'm pretty new to making bot thing so I have several questions I want to ask regarding this:
I'm using a bot to send message by
def send_message(chat_id, msg):
url = f"https://api.telegram.org/bot{bot_token}/sendMessage?chat_id={chat_id}&text={msg}"
requests.get(url)
send_message(chat_id,msg)
By this, I can send message and I want to beautify the result by using parse_mode but I don't know where to put in in url to make it work.
I'm alternate to using Telethon. I can use it to send message to individual and group by user name and group invite link, but when I try to send it to channel by:
client.send_message(entity='my channel name', message=message)
When I try to run it, it return Cannot find any entity corresponding to "Test channel".
I also try
destination_channel_username='test_ali3'
entity=client.get_entity(destination_channel_username)
client.send_message(entity=entity,message="Hi")
but it require my channel access_hash, how can get it, or are there any other way to send message to channel.
I know Telegram bot API have function like sendMessage or bot.sendMessage that also can do the job, but somehow I can't call it, which packages should I install and/or import.
Thanks a lot!
This should do the trick:
def send_message(chat_id, msg, parse_mode):
url = f"https://api.telegram.org/bot{bot_token}/sendMessage?chat_id={chat_id}&text={msg}&parse_mode={parse_mode}"
requests.get(url)
TBH I'm not too familiar with telethon, but that library is mainly intended for so called userbots. that means that it uses the API that also the Telegram app uses and because of that, it's often times more involved than just the plain bot api.
To use the Bot API in Python, I can recommend the package python-telegram-bot, see https://python-telegram-bot.org. Disclaimer: I'm currently the maintainer of that package. There are also other python packages for the bot api, see e.g. https://core.telegram.org/bots/samples#python
Using discord's search function manually, you can enter something like from:user#3456 and it will show you how many messages they've sent on the server (at least, messages you have access to).
I've been told there is no way to get this information through discord.py, but is there really no way to get that data at all? Would I have to resort to a web scraping tool?
To be clear, I have looked at history() already. What I'm looking for is a way to access the search function that Discord already has.
This is actually possible using discord.TextChannel.history. Here is an example:
userMessages = []
userID = 1234567890 # Change this to the ID of the user you are looking messages for
channelID = 1234567890 # Change this to the channel ID of the messages you want to check for
channel = client.get_channel(channelID)
user = discord.utils.find(lambda m: m.id== userID, channel.guild.members)
async for message in channel.history():
if message.author == user:
userMessages.append(message.content)
print(len(userMessages)) # Outputs total user messages
Make sure you replace 1234567890 with the corresponding IDs.
I've added an array which also shows all the user messages, if you prefer you can remove that and have it increment a counter instead.
I solved this in a kind of hacky way by searching with a from:username query in the Discord app, looking at the http request with Chrome DevTools, and finally recreating the request with the python module requests.
In Discord in a browser, you can open DevTools with the f12 key.
In DevTools, navigate to the Network tab.
I'd suggest to fill in the search query (but don't hit enter), then open devtools, then hit enter on the search. Otherwise there will be a lot of http requests that pop up as you type.
Then, you find the request with a name that looks like "search?author_id=1234567890". If you click on that request, you can see the details necessary to recreate it.
The key parts of the http request you need to use are the Request Headers section and the Request URL under the General section, all in the Headers tab that pops up when you first click on the request, and the Response tab to see what your response will look like.
The accept-encoding attribute of the Request Headers includes br, but this seems to jumble the result. Keeping it to just gzip, deflate works for me.
Using the requests python module this should be pretty easy to set up. So long as br is not listed in accepted-encoding, you should be able to use the json() method of requests, and for the particular problem of finding the total messages sent by the user (whose id you must insert into the request URL), it's simply accessible with my_request_variable.json()['total_results'].
The main thing to watch out for is the authorization request header. This is unique to the user (you, unless you do all this from someone else's account) and you can't substitute in a discord bot's token, unfortunately.
Everyday, a sender "sender#sender.com" send me a message with a number inside.
I need to save this number everyday.
I want to write a python script with gmail API to get data from last mail from this sender, and then parse it.
I followed the Gmail API "Quickstart Guide" : here
I also check the page about User.message : here
However, I don't understand how to synchronize all of this to get the data.
Could someone explain me the process ?
If you where you able to complete the Gmail API quickstart, then you already have a GCP project, credentials and have authorized some Gmail API scopes for you app.
The above is the first step (being able to authenticate and be allowed to make requests for the API scope you need).
Since you need to pass a message's Id as a parameter for Users.messages.get you need to first retrieve it using listing messages for example.
So the next step is to make a request to Users.messages.list to list all messages from a user.
You could use the query (q) parameter to filter the messages by user like: q="from:someuser#example.com is:unread".
This will return a list of messages from someuser#example.com that are unread.
Try things out in the API explorer sidebar from the documentation until you have defined the request as you want, and then implement it into you app.
As aerials said.
users().messages().list(userId='me',q=("<parameters>"))).execute()
The above code will fulfill the exact same function as typing in a search request on the gmail website. You dont actually have to worry about labels or anything if you are operating at a small scale. Just follow the same syntax as the search bar on gmail.
However, I am not sure about the usage quotas on the q parameter for list. It may be more expensive for a bigger scale operation to use the q parameter instead of using the other api methods.
I want to send an order to oanda to make a transaction,I use ipython notebook to compile my code,this is my code:
import oandapy
trade_expire=datetime.now()+timedelta(days=1)
trade_expire=trade_expire.isoformat("T")+"Z"
oanda=oandapy.API(environment='practice',access_token='XXXX....')
account_id=xxxxxxx
response=oanda.create_order(account_id,instrument='USD_EUR',units=1000,side='buy',/
type='limit',price=1.105,expire=trade_expire)
But the error is:
OandaError: OANDA API returned error code 4 (The access token provided does
not allow this request to be made)
How can I solve this problem?
I had the same problem, but when sending orders via curl commands.
The problem has to do with which API you are using from which account.
I notice in your python it says "practice," so you'll want to make sure the API token you generated is from within your practice account. Live accounts and practice accounts each use their own API tokens, and your commands will need to match.
You might also look elsewhere in your python, where it actually pings OandA's server.
For example, when using curl, a live account uses
"https://api-fxtrade.oanda.com/v3/accounts/<ACCOUNT>/orders"
and a practice account uses
"https://api-fxpractice.oanda.com/v3/accounts/<ACCOUNT>/orders"
Using your API token generated on your live account in a practice account will produce the error you're asking about.
We need to implement a bot which posts new sections on Wikipedia Talk pages.
As a matter of efficiency, we prefer to use python HTTP POST requests using MediaWiki API rather than available MediaWiki libraries.
We have not requested for an approval for the bot, and we are just trying to implement a trial version to test the bot on our own Talk pages.
For this purpose, I went through the following steps:
1- As discussed at https://en.wikipedia.org/wiki/Wikipedia:Creating_a_bot:
Create an account for your bot. Click here when logged in to create the account, linking it to yours. (If you do not create the bot account while logged in, it is likely to be blocked as a possible sockpuppet or unauthorised bot until you verify ownership)
Create a user page for your bot. Your bot's edits must not be made under your own account. Your bot will need its own account with its own username and password.
So, I logged in to my own Wikipedia account, and created a new account (for the bot).
2- As discussed at "API:Login" page: (Sorry, because of having less than 10 reputation, I am not able to add more than 2 links)
Logging in through the API requires two requests. For the first request, I wrote the following code in python:
def logInRequestToWikipedia():
# Add required parameters to the request.
request = { 'action' : 'login' }
request['lgname'] = 'BotName'
request['lgpassword'] = '*************'
url = 'https://en.wikipedia.org/w/api.php'
headers = { 'content-type' : 'application/x-www-form-urlencoded' }
r = requests.post(url, data = json.dumps(request), headers=headers)
The response starts with an error as follows:
<error code="help" info="" xml:space="preserve">
And continues with the API documentation.
3- As discussed at "API:Edit_-_Create%26Edit_pages" page:
Note: In this example, all parameters are passed in a GET request just for the sake of simplicity. However, action=edit requires POST requests; GET requests will cause an error. Do not forget to set the Content-Type header of your request to application/x-www-form-urlencoded. The token that you received is terminated with +\, this needs to be urlencoded (so it will end with %2B%5C) before it is passed back.
I added each of the following parameters separately and both together in the request data and tried all three cases, but it returns the same response.
request['lgtoken'] = '%2B%5C'
request['Content-Type'] = 'application/x-www-form-urlencoded'
4- Also I tried each of the followings in my request data, but it returns the same response:
request['format'] = 'json'
request['format'] = 'xml'
5- Moreover I found the following instruction at "User-Agent_policy" page:
User agents (browsers or scripts) that do not send a User-Agent header may now encounter an error message like this:
Scripts should use an informative User-Agent string with contact information, or they may be IP-blocked without notice.
User agents that send a User-Agent header that is blacklisted (for example, any User-Agent string that begins with "lwp", whether it is informative or not) may encounter a less helpful error message (lie) like this:
Our servers are currently experiencing a technical problem. This is probably temporary and should be fixed soon. Please try again in a few minutes.
This change is most likely to affect scripts (bots) accessing Wikimedia websites such as Wikipedia automatically, via api.php or otherwise, and command line programs.[3] If you run a bot, please send a User-Agent header identifying the bot and supplying some way of contacting you, e.g.:
User-Agent: MyCoolTool/1.1 (http://example.com/MyCoolTool/; MyCoolTool#example.com) BasedOnSuperLib/1.4
Do not copy a browser's user agent for your bot, as bot-like behavior with a browser's user agent will be assumed malicious.[4] For more information, please refer to the MediaWiki API Documentation
That's why I also tried my script with the following parameter, but the error response did not change:
request['User-Agent'] = "MyCoolTool/1.1 (http://example.com/MyCoolTool/; MyCoolTool#example.com) BasedOnSuperLib/1.4"
Do you think the problem can be related to the fact that we have not requested for an approval for the bot yet? Because we are just trying to implement a trial version to test the bot on our own Talk pages, and apply for the approval after making sure everything will work.
I'm pretty sure the problem is this line:
request['lgtoken'] = '%2B%5C'
The Login API you linked to doesn't include an lgtoken on the initial login attempt; it's only sent on the second ("Confirm token") step, using the token value from the NeedToken response.
And +\ doesn't look like a valid token.
So it's not surprising that you're getting an error.
Meanwhile, when I test this with my Wikipedia account, I get an error if I include that line, and success if I don't, which validates my suspicion that this is the problem.