C# – Tweet API v2 – 将媒体附加到推文 / 创建 JsonProperty

huangapple go评论152阅读模式
英文:

C# - Tweet API v2 - Attach Media to Tweet / Create JsonProperty

问题

Here's the translation of the code portion you provided:

对于你的信息,我正在使用"TweetinviAPI (5.0.4)" NuGet 包。

我在这里找到了与发布带媒体推文相关的信息,但我不知道如何在 C# 中使用它:

https://developer.twitter.com/en/docs/twitter-api/tweets/manage-tweets/api-reference/post-tweets

[这里有一个示例 --> media.media_ids](https://i.stack.imgur.com/VFz8H.png)

----------------------------------------------------------------------------------------------------

目前我有一个名为"text" JsonProperty。它完全正常工作。这是我的 "Poster" 类:

namespace MainData.Twitter_API_v2
{
    public class TweetsV2Poster
    {
        private readonly ITwitterClient client;

        public TweetsV2Poster(ITwitterClient client)
        {
            this.client = client;
        }

        public Task<ITwitterResult> PostTweet(TweetV2PostRequest tweetParams)
        {
            return this.client.Execute.AdvanceRequestAsync(
                (ITwitterRequest request) =>
                {
                    var jsonBody = this.client.Json.Serialize(tweetParams);

                    var content = new StringContent(jsonBody, Encoding.UTF8, "application/json");
                    request.Query.Url = "https://api.twitter.com/2/tweets";
                    request.Query.HttpMethod = Tweetinvi.Models.HttpMethod.POST;
                    request.Query.HttpContent = content;
                }
            );
        }
    }

    public class TweetV2PostRequest
    {
        /// <summary>
        /// 要发布的推文文本。
        /// </summary>
        [JsonProperty("text")]
        public string Text { get; set; } = string.Empty;
    }
}

----------------------------------------------------------------------------------------------------

这里我正在调用 "Poster" 类:

// 获取 byte[] --> itemshopImg
GetItemshopImage dailyData = new GetItemshopImage();
var itemshopImg = dailyData.GetItemshopImg();

// 创建 Twitter 客户端
var client = new TwitterClient(
                "x",
                "x",
                "x",
                "x"
            );

// 上传推文图片
var tweetItemshopImg = await client.Upload.UploadTweetImageAsync(itemshopImg);

// 发布推文
var poster = new TweetsV2Poster(client);
ITwitterResult result = await poster.PostTweet(
    new TweetV2PostRequest
    {
        Text = "myText"
    });

----------------------------------------------------------------------------------------------------
我的目标是使用 "tweetItemshopImg" 变量中的 Id(在开头的图片中的 media.id)并将其传递给 "TweetsV2Poster" 类内部的 JSON 属性。

Please note that I've translated the code portion for you, as requested.

英文:

for your information Im using the"TweetinviAPI (5.0.4)" nugget package

I found here something related to post a tweet with media, but I dont know how to use it in C#:

https://developer.twitter.com/en/docs/twitter-api/tweets/manage-tweets/api-reference/post-tweets

Here is an example --> media.media_ids


At the moment I have an JsonProperty called "text".
That works totally fine. Here is my "Poster" Class:

namespace MainData.Twitter_API_v2
{
public class TweetsV2Poster
{
private readonly ITwitterClient client;
public TweetsV2Poster(ITwitterClient client)
{
this.client = client;
}
public Task&lt;ITwitterResult&gt; PostTweet(TweetV2PostRequest tweetParams)
{
return this.client.Execute.AdvanceRequestAsync(
(ITwitterRequest request) =&gt;
{
var jsonBody = this.client.Json.Serialize(tweetParams);
var content = new StringContent(jsonBody, Encoding.UTF8, &quot;application/json&quot;);
request.Query.Url = &quot;https://api.twitter.com/2/tweets&quot;;
request.Query.HttpMethod = Tweetinvi.Models.HttpMethod.POST;
request.Query.HttpContent = content;
}
);
}
}
public class TweetV2PostRequest
{
/// &lt;summary&gt;
/// The text of the tweet to post.
/// &lt;/summary&gt;
[JsonProperty(&quot;text&quot;)]
public string Text { get; set; } = string.Empty;
}
}

And here I'm calling the "Poster" Class:

//Get the byte[] --&gt; itemshopImg
GetItemshopImage dailyData = new GetItemshopImage();
var itemshopImg = dailyData.GetItemshopImg();
//Create Twitter Client
var client = new TwitterClient(
&quot;x&quot;,
&quot;x&quot;,
&quot;x&quot;,
&quot;x&quot;
);
//Upload Tweet Image
var tweetItemshopImg = await client.Upload.UploadTweetImageAsync(itemshopImg);
//Post Tweet
var poster = new TweetsV2Poster(client);
ITwitterResult result = await poster.PostTweet(
new TweetV2PostRequest
{
Text = &quot;myText&quot;
});

My goal is to use the Id (media.id in the Image at the beginning) from the "tweetItemshopImg" variable and give it the to an JSON Property inside the "TweetsV2Poster" class.

答案1

得分: 0

Here's the translated code part:

{
    "text": "Tweeting with media!",
    "media": {
        "media_ids": [
            "1455952740635586573"
        ]
    }
}

Modify your `TweetV2PostRequest` as follows:

public class TweetV2PostRequest
{
    /// <summary>
    /// The text of the tweet to post.
    /// </summary>
    [JsonProperty("text")]
    public string Text { get; set; } = string.Empty;

    [JsonProperty("media", NullValueHandling = NullValueHandling.Ignore)]
    public TweetV2Media? Media { get; set; }
}

public class TweetV2Media
{
    [JsonIgnore]
    public List<long>? MediaIds { get; set; }

    [JsonProperty("media_ids", NullValueHandling = NullValueHandling.Ignore)]
    public string[]? MediaIdStrings
    {
        get => MediaIds?.Select(i => JsonConvert.ToString(i)).ToArray();
        set => MediaIds = value?.Select(s => JsonConvert.DeserializeObject<long>(s)).ToList();
    }

    // Add others here as required, setting NullValueHandling.Ignore or DefaultValueHandling = DefaultValueHandling.Ignore to suppress unneeded properties
}

And call `poster.PostTweet()` as follows:

// Post Tweet
// tweetItemshopImg.Id is a Nullable<long>
var poster = new TweetsV2Poster(client);
ITwitterResult result = await poster.PostTweet(
    new TweetV2PostRequest
    {
        Text = "Tweeting with media!",
        Media = tweetItemshopImg?.Id == null ? null : new () { MediaIds = new () { tweetItemshopImg.Id.Value } }
    });

Notes:

- It seems that [tag:tweetinvi] does not currently have support for posting tweets with associated media using the Twitter V2 API. A [search](https://github.com/linvi/tweetinvi/search?q=BaseTweetsV2Parameters) of the source code for `BaseTweetsV2Parameters` turns up several derived types such as `GetTweetsV2Parameters` -- but no `PostTweetsV2Parameters`.

- To confirm the correct JSON was generated, I modified `TweetsV2Poster` as follows:

public Task<ITwitterResult> PostTweet(TweetV2PostRequest tweetParams)
{
    return this.client.Execute.AdvanceRequestAsync(
        (ITwitterRequest request) =>
        {
            var jsonBody = this.client.Json.Serialize(tweetParams);

            Debug.WriteLine(JToken.Parse(jsonBody));

            Assert.That(JToken.Parse(jsonBody).ToString() == JToken.Parse(GetRequiredJson()).ToString());

            var content = new StringContent(jsonBody, Encoding.UTF8, "application/json");
            request.Query.Url = "https://api.twitter.com/2/tweets";
            request.Query.HttpMethod = Tweetinvi.Models.HttpMethod.POST;
            request.Query.HttpContent = content;
        }
    );
}

static string GetRequiredJson() =>
    @"
    {
       ""text"": ""Tweeting with media!"",
       ""media"": {
          ""media_ids"": [
             ""1455952740635586573""
          ]
       }
    }";

I've translated the code while keeping the code structure and JSON intact.

英文:

To generate the JSON sample shown in the documentation:

{
&quot;text&quot;:&quot;Tweeting with media!&quot;,
&quot;media&quot;:{
&quot;media_ids&quot;:[
&quot;1455952740635586573&quot;
]
}
}	

Modify your TweetV2PostRequest as follows:

public class TweetV2PostRequest
{
/// &lt;summary&gt;
/// The text of the tweet to post.
/// &lt;/summary&gt;
[JsonProperty(&quot;text&quot;)]
public string Text { get; set; } = string.Empty;
[JsonProperty(&quot;media&quot;, NullValueHandling = NullValueHandling.Ignore)]
public TweetV2Media? Media { get; set; }
}
public class TweetV2Media
{
[JsonIgnore]
public List&lt;long&gt;? MediaIds { get; set; }
[JsonProperty(&quot;media_ids&quot;, NullValueHandling = NullValueHandling.Ignore)]
public string []? MediaIdStrings { 
get =&gt; MediaIds?.Select(i =&gt; JsonConvert.ToString(i)).ToArray(); 
set =&gt; MediaIds = value?.Select(s =&gt;JsonConvert.DeserializeObject&lt;long&gt;(s)).ToList(); }
// Add others here as required, setting NullValueHandling.Ignore or DefaultValueHandling = DefaultValueHandling.Ignore to suppress unneeded properties
}

And call poster.PostTweet() as follows:

//Post Tweet
// tweetItemshopImg.Id is a Nullable&lt;long&gt;
var poster = new TweetsV2Poster(client);
ITwitterResult result = await poster.PostTweet(
new TweetV2PostRequest
{
Text = &quot;Tweeting with media!&quot;,
Media = tweetItemshopImg?.Id == null ? null : new () { MediaIds = new () { tweetItemshopImg.Id.Value } }
});

Notes:

  • It seems that [tag:tweetinvi] does not currently have support for posting tweets with associated media using the Twitter V2 API. A search of the source code for BaseTweetsV2Parameters turns up several derived types such as GetTweetsV2Parameters -- but no PostTweetsV2Parameters.

  • To confirm the correct JSON was generated, I modified TweetsV2Poster as follows:

    public Task&lt;ITwitterResult&gt; PostTweet(TweetV2PostRequest tweetParams)
    {
    return this.client.Execute.AdvanceRequestAsync(
    (ITwitterRequest request) =&gt;
    {
    var jsonBody = this.client.Json.Serialize(tweetParams);
    Debug.WriteLine(JToken.Parse(jsonBody));
    Assert.That(JToken.Parse(jsonBody).ToString() == JToken.Parse(GetRequiredJson()).ToString());
    var content = new StringContent(jsonBody, Encoding.UTF8, &quot;application/json&quot;);
    request.Query.Url = &quot;https://api.twitter.com/2/tweets&quot;;
    request.Query.HttpMethod = Tweetinvi.Models.HttpMethod.POST;
    request.Query.HttpContent = content;
    }
    );
    }
    static string GetRequiredJson() =&gt; 
    &quot;&quot;&quot;
    {
    &quot;text&quot;:&quot;Tweeting with media!&quot;,
    &quot;media&quot;:{
    &quot;media_ids&quot;:[
    &quot;1455952740635586573&quot;
    ]
    }
    }	
    &quot;&quot;&quot;;
    

    There was no assert, indicating the JSON matched the sample (aside from formatting).

  • Tweetinvi does not document the JSON serializer it uses, however its nuget has a dependency on Newtonsoft.Json indicating that is the serializer currently used.

huangapple
  • 本文由 发表于 2023年5月21日 04:48:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/76297300.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定