GithubHelp home page GithubHelp logo

mkellerman / pstwitterapi Goto Github PK

View Code? Open in Web Editor NEW
45.0 45.0 14.0 423 KB

PSTwitterAPI - a PowerShell module for the Twitter API

Home Page: https://mkellerman.github.io/Introducing_PSTwitterAPI/

PowerShell 100.00%

pstwitterapi's People

Contributors

ctmcisco avatar kamsalisbury avatar mkellerman avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

pstwitterapi's Issues

Error thrown when POST-ing large payload

I'm trying to use Send-TwitterAccount_UpdateProfileBanner to update my account banner:

$Image = [Convert]::ToBase64String((Get-Content .\TwitterBanner.png -Encoding Byte))
Send-TwitterAccount_UpdateProfileBanner -banner $Image

Naturally, that Image string is HUGE, as I'm trying to send a 1500x500 image (the recommended size for one of these banners) that's 101 KB on disk.

When run, I get back

Get-OAuthParameters : Exception calling "EscapeDataString" with "1" argument(s): "Invalid URI: The Uri string is too long."
At C:\Users\joshuak\Documents\WindowsPowerShell\Modules\PSTwitterAPI\0.0.7\public\Invoke-TwitterAPI.ps1:26 char:24
+     $OAuthParameters = Get-OAuthParameters @OAuthParameters_Params
+                        ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Write-Error], WriteErrorException
    + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,Get-OAuthParameters
 
Invoke-RestMethod : Cannot bind parameter 'Method' to the target. Exception setting "Method": "Cannot convert null to type "Microsoft.PowerShell.Commands.WebRequestMethod" due to enumeration 
values that are not valid. Specify one of the following enumeration values and try again. The possible enumeration values are "Default,Get,Head,Post,Put,Delete,Trace,Options,Merge,Patch"."
At C:\Users\joshuak\Documents\WindowsPowerShell\Modules\PSTwitterAPI\0.0.7\public\Invoke-TwitterAPI.ps1:34 char:23
+     Invoke-RestMethod @RestMethod_Params
+                       ~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : WriteError: (:) [Invoke-RestMethod], ParameterBindingException
    + FullyQualifiedErrorId : ParameterBindingFailed,Microsoft.PowerShell.Commands.InvokeRestMethodCommand

Looks like the entire image payload is being encoded as part of the URI... which if my understanding of that class is right is capped at 2048 characters? I've tried halving the size of the image, but it's still too long.

I think that shipping this data up as a JSON body on Invoke-RESTMethod would get it up there (I was playing around with this a little, but mucked up the authentication side of things lol)

Create missing API Helper cmdlets

  • POST statuses/update_with_media
  • GET statuses/oembed
  • POST media/upload
  • POST media/upload chunked
  • GET direct_messages/sent
  • GET direct_messages/show
  • GET direct_messages
  • POST direct_messages/destroy
  • POST direct_messages/new
  • GET friendships/no_retweets/ids
  • GET friendships/incoming
  • GET friendships/outgoing
  • POST friendships/create
  • POST friendships/destroy
  • POST friendships/update
  • GET friendships/show
  • GET friends/list
  • GET followers/list
  • GET friendships/lookup
  • GET account/settings
  • GET account/verify_credentials
  • POST account/settings
  • POST account/update_delivery_device
  • POST account/update_profile
  • POST account/update_profile_background_image
  • POST account/update_profile_image
  • GET blocks/list
  • GET blocks/ids
  • POST blocks/create
  • POST blocks/destroy
  • GET users/show
  • GET users/search
  • POST account/remove_profile_banner
  • POST account/update_profile_banner
  • GET users/profile_banner
  • POST mutes/users/create
  • POST mutes/users/destroy
  • GET mutes/users/ids
  • GET mutes/users/list
  • GET users/suggestions/:slug
  • GET users/suggestions
  • GET users/suggestions/:slug/members
  • GET favorites/list
  • POST favorites/destroy
  • POST favorites/create
  • GET lists/statuses
  • POST lists/members/destroy
  • GET lists/memberships
  • GET lists/subscribers
  • POST lists/subscribers/create
  • GET lists/subscribers/show
  • POST lists/subscribers/destroy
  • POST lists/members/create_all
  • GET lists/members/show
  • GET lists/members
  • POST lists/members/create
  • POST lists/destroy
  • POST lists/update
  • POST lists/create
  • GET lists/show
  • GET lists/subscriptions
  • POST lists/members/destroy_all
  • GET lists/ownerships
  • GET saved_searches/list
  • GET saved_searches/show/:id
  • POST saved_searches/create
  • POST saved_searches/destroy/:id
  • GET geo/id/:place_id
  • GET geo/reverse_geocode
  • GET geo/search
  • POST geo/place
  • GET trends/place
  • GET trends/available
  • GET help/configuration
  • GET help/languages
  • GET help/privacy
  • GET help/tos
  • GET trends/closest
  • POST users/report_spam

Azure pipelines Install module -Force

When installing the current version during Azure Pipelines release, it's necessary to use the -Force parameter:

Install-PackageProvider -Name PSTwitterAPI -Force -Scope CurrentUser

The build server is stateless so the module hasn't been installed before.
In this case, -Force along with no previous module installation, results in the error:
During module import on Exporting function Set-TwitterOAuthSettings

"No OAuthSettings was found. Use 'Set-TwitterOAuthSettings' to set PSTwitterAPI ApiKey & Token."

Could you remove the throw on the next update so that it's possible to use the PS Gallery version again?

https://github.com/whiteken/NSTrainTime/blob/master/PSTwitterAPI/0.0.7/public/Get-TwitterOAuthSettings.ps1

Otherwise the module is fantastic... saved me a tonne of time - thanks :)

Secret Access Token not accepted

I might be doing something wrong as the tutorial sadly isn't very detailed but I'm getting an error trying to set up PSTwitterAPI. I installed it just fine and then edited my PowerShell startup script by adding:

Import-Module PSTwitterAPI

$OAuthSettings = @{
  "MYAPIKEY" = $env:ApiKey
  "MYAPISECRET" = $env:ApiSecret
  "MYACCESSTOKEN" = $env:AccessToken
  "MYACCESSTOKENSECRET" =$env:AccessTokenSecret
}
Set-TwitterOAuthSettings @OAuthSettings

The first three keys seem to check out but the last one returns an error akin to "Invalid value for AccessTokenSecret, no value was assigned". I had to paraphrase as my Windows is set to German. Did I add the keys wrong? I'm new to PowerShell.

EDIT: I thought I would add the exact error message in German:
Set-TwitterOAuthSettings : Es wurde kein Parameter gefunden, der dem Parameternamen "MYACCESSTOKENSECRET" entspricht.

A better translation would be:

There is no parameter that matches the parameter-name "MYACCESSTOKENSECRET". It shows the actual token there to clarify but of course I won't post that online.

Import-Module -Name PSTwitterAPI is slow to load

Currently, I'm using this command to generate the list of CmdletBindingParameters that is generated by using [CmdletBinding()]. We want to eliminate this when using the parameters for our TwitterAPI generated by the APIHelper.

$Script:CmdletBindingParameters = (Get-Command 'Get-Culture').Parameters.Keys

Needs to be replaced by static list to improve loading speeds.

Currently takes ~2.5 seconds to load.

Error calling Send-TwitterDirectMessages_EventsNew: Bad Authentication Data

Any idea why I am getting this error calling Send-TwitterDirectMessages_EventsNew?

Code:

$TwitterUser = Get-TwitterUsers_Lookup -screen_name 'chinhdo'
$Event = Send-TwitterDirectMessages_EventsNew -recipient_id $TwitterUser.Id -text "Hello !!"

The Get-TwitterUsers_Lookup method works fine. But the Send-TwitterDirectMessages_EventsNew errored out with the below. I did configure the app permissions to allow Read + Write + Direct Messages.

Invoke-RestMethod : {"errors":[{"code":215,"message":"Bad Authentication data."}]}
At C:\Program Files\WindowsPowerShell\Modules\PSTwitterAPI\0.0.8\public\Invoke-TwitterAPI.ps1:34 char:5
+     Invoke-RestMethod @RestMethod_Params
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebExceptio  
   n
    + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand
WARNING: Throttling for -1626964553.70296 seconds.
Start-Sleep : Cannot validate argument on parameter 'Seconds'. The -1626964554 argument is less than the minimum allowed 
range of 0. Supply an argument that is greater than or equal to 0 and then try the command again.
At C:\Program Files\WindowsPowerShell\Modules\PSTwitterAPI\0.0.8\public\Get-TwitterOAuthSettings.ps1:33 char:38
+                 Start-Sleep -Seconds $SleepSeconds
+                                      ~~~~~~~~~~~~~
    + CategoryInfo          : InvalidData: (:) [Start-Sleep], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.PowerShell.Commands.StartSleepCommand

Thanks

SendTweetAsync ID is zero

Hello again,

I wrote a powershell wrapper (to explain the next format) that executes fine however the tweet ID remain zero and I am want it for further actions like retweet etc.. Am I missing something?

        protected override Task EndProcessingAsync(){
            return TwitterContext.TweetAsync(Status,_medias.Select(media => media.MediaID)).ToObservable()
                .HandleErrors(this)
                .WriteObject(this)
                .ToTask();
        }
Type                      : User
ID                        : 0
UserID                    : 0
ScreenName                :
SinceID                   : 0
MaxID                     : 0
Count                     : 0
Cursor                    : 0
IncludeRetweets           : False
ExcludeReplies            : False
IncludeEntities           : False
IncludeUserEntities       : False
IncludeMyRetweet          : False
IncludeAltText            : False
OEmbedUrl                 :
OEmbedMaxWidth            : 0
OEmbedHideMedia           : False
OEmbedHideThread          : False
OEmbedOmitScript          : False
OEmbedAlign               : None
OEmbedRelated             :
OEmbedLanguage            :
CreatedAt                 : 4/23/2020 11:32:57 AM
StatusID                  : 1253285727498010624
Text                      : The A��-������������������������� #XpandPwsh                            PowerShell CmdLet:

                            Filter out warnings for a PackageReference.

                            Wiki… https://t.co/r6JRAEQdfT
FullText                  :
ExtendedTweet             : LinqToTwitter.Status
Source                    : <a href="http://www.expandframework.com" rel="nofollow">MSBuild Teamcity</a>
Truncated                 : True
DisplayTextRange          :
TweetMode                 : Compat
InReplyToStatusID         : 0
InReplyToUserID           : 0
FavoriteCount             : 0
Favorited                 : False
InReplyToScreenName       :
User                      : LinqToTwitter.User
Users                     : {}
Contributors              : {}
Coordinates               : LinqToTwitter.Coordinate
Place                     : LinqToTwitter.Place
Annotation                : LinqToTwitter.Annotation
Entities                  : LinqToTwitter.Entities
ExtendedEntities          : LinqToTwitter.Entities
TrimUser                  : False
IncludeContributorDetails : False
RetweetCount              : 0
Retweeted                 : False
PossiblySensitive         : False
RetweetedStatus           : LinqToTwitter.Status
CurrentUserRetweet        : 0
IsQuotedStatus            : False
QuotedStatusID            : 0
QuotedStatus              : LinqToTwitter.Status
Scopes                    : {}
WithheldCopyright         : False
WithheldInCountries       : {}
WithheldScope             :
MetaData                  : LinqToTwitter.StatusMetaData
Lang                      : en
Map                       : False
TweetIDs                  :
FilterLevel               : None
EmbeddedStatus            :
CursorMovement            :

running Set-TwitterOAuthSettings in script

I have this in script:
$ErrorActionPreference = 'Continue'

try {
Import-Module PSTwitterAPI
Set-TwitterOAuthSettings -ApiKey 'xx' -ApiSecret 'xx' -AccessToken 'xx' -AccessTokenSecret 'xx'
...

this causes error:
No OAuthSettings was found. Use 'Set-TwitterOAuthSettings' to set PSTwitterAPI ApiKey & Token.
At C:\Program Files\WindowsPowerShell\Modules\PSTwitterAPI\0.0.7\public\Get-TwitterOAuthSettings.ps1:35 char:9

  •     Throw "No OAuthSettings was found. Use 'Set-TwitterOAuthSetti ...
    
  •     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
    • CategoryInfo : OperationStopped: (No OAuthSetting...ApiKey & Token.:String) [], RuntimeException
    • FullyQualifiedErrorId : No OAuthSettings was found. Use 'Set-TwitterOAuthSettings' to set PSTwitterAPI ApiKey & Token.

looks like erroraction part in Set-TwitterOAuthSettings in script is being ignored.
...
If ($OAuthSettings = Get-TwitterOAuthSettings -AccessToken $AccessToken -ErrorAction SilentlyContinue)
...

If I remove throw from Get-TwitterOAuthSettings, it works.

Set-TwitterOAuthSettings works when run on command line..?

How do I upload a jpg and tweet that?

$file = "D:\OneDrive\Desktop\images\New_folder\Abedour.jpg"
$length = (get-item $file).Length
Send-TwitterMedia_Upload -command INIT -total_bytes $length -media_type image/jpeg 

this returns the media.id, but I cant see the syntax for Send-TwitterStatuses_UpdateWithMedia to actually upload and post?

Send-TwitterBlocks_Create code 215 Bad Authentication data

Send-TwitterBlocks_Create -screen_name $screenname

Some other commands works fine so I know the oauth is working.

I get this error
BadRequest
{"errors":[{"code":215,"message":"Bad Authentication data."}]}

at Microsoft.PowerShell.Commands.WebRequestPSCmdlet.GetResponse(WebRequest request)
at Microsoft.PowerShell.Commands.WebRequestPSCmdlet.ProcessRecord()

Invalid URL in function Send-TwitterBlocks_Destroy $ResourceUrl

Hi,

There is a rogue 'POST' in the $ResourceUrl for this function, causing it to error on execution.

PS C:\Users\Martin> Get-TwitterBlocks_Ids


ids                 : {1129359659653971969, 1180924045157687296}
next_cursor         : 0
next_cursor_str     : 0
previous_cursor     : 0
previous_cursor_str : 0
total_count         : 




PS C:\Users\Martin> Send-TwitterBlocks_Destroy -user_id 1180924045157687296
Invoke-RestMethod : Invalid URI: The hostname could not be parsed.
At D:\Users\Martin\Documents\WindowsPowerShell\Modules\PSTwitterAPI\0.0.7\public\Invoke-TwitterAPI.ps1:34 char:5
+     Invoke-RestMethod @RestMethod_Params
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Invoke-RestMethod], UriFormatException
    + FullyQualifiedErrorId : System.UriFormatException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand
 

PS C:\Users\Martin> 

image

Thanks,
Martin

Project School

For a project at school I'll be using this API which will make my life a lot easier. Whilst setting up the API I came across a Problem. I am a rookie if it comes to PowerShell so this is probably an easy fix but I can't seem to find it. When I want to import the module I get the error that it cannot be loaded because running scripts is disabled on this system.

Can someone tell me what i need to do exactly?

image

In addition to the project, can someone tell me how i can search for tweets using a specific hashtag?

Thank you in advance
Toon Staes

Remove the requirement for both $Resource and $ResourceURL parameters

In the function Invoke-TwitterAPI, we require 2 parameters:

Name Example
$Resource /statuses/update
$ResourceUrl https://api.twitter.com/1.1/statuses/update.json

$Resource is used to find the RateLimitStatus on that resource. And $ResourceUrl is used to build the OAuthSettings.

But some resources are like this:

    [string]$Resource    = '/geo/id/:place_id'
    [string]$ResourceUrl = 'https://api.twitter.com/1.1/geo/id/:place_id.json'

And I need to replace :place_id in the ResourceUrl with the actual value of the place_id parameter.

    [string]$ResourceUrl = https://api.twitter.com/1.1/geo/id/df51dec6f4ee2b2c.json

I suspect that I will need to generate the $Resource from the $ResourceUrl.
If I don't find a resource with the full text, then look for partial match.

I would like to have to only supply one parameter, so less parameters are required to do manual Invoke-TwitterAPI commands.

Create Pester tests for API Helper cmdlets

  • Get-TwitterApplication_RateLimitStatus
  • Get-TwitterFollowers_IDs
  • Get-TwitterFriends_IDs
  • Get-TwitterLists_list
  • Get-TwitterLists_Subscriptions
  • Get-TwitterSearch_Tweets
  • Get-TwitterStatuses_HomeTimeline
  • Get-TwitterStatuses_Lookup
  • Get-TwitterStatuses_MentionsTimeline
  • Get-TwitterStatuses_Retweeters_IDs
  • Get-TwitterStatuses_RetweetsID
  • Get-TwitterStatuses_RetweetsOfMe
  • Get-TwitterStatuses_ShowID
  • Get-TwitterStatuses_UserTimeline
  • Get-TwitterUser_Lookup
  • Send-TwitterStatuses_DestroyID
  • Send-TwitterStatuses_RetweetID
  • Send-TwitterStatuses_UnretweetID
  • Send-TwitterStatuses_Update

Remove all `_` from function names

It is a standard practice that no _ or - (other than between Verb-Noun ) are used in function names

Therefore this issue is to raise about removing them to fall inline with standard PowerShell Practices

Get-TwitterStatuses_UserTimeline not displaying full_text

I believe there is a parameter tweet_extended which can be set to yes/no but I am not sure how to pull and fix that. It might also be a matter of requesting full_text vs text according to what I have read. Is it simply a matter of updating the API JSON file?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.