C# - Tweet API v2 -将媒体附加到Tweet /创建JsonProperty

r7knjye2  于 2023-05-23  发布在  C#
关注(0)|答案(1)|浏览(163)

供您参考,我使用的是”TweetinviAPI(5.0.4)”nugget包
我在这里找到了一些与媒体发布推文相关的东西,但我不知道如何在C#中使用它:
https://developer.twitter.com/en/docs/twitter-api/tweets/manage-tweets/api-reference/post-tweets
Here is an example --> media.media_ids
目前我有一个JsonProperty,叫做“text”。完全没问题。以下是我的“海报”类:

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>
        /// The text of the tweet to post.
        /// </summary>
        [JsonProperty("text")]
        public string Text { get; set; } = string.Empty;
    }
}

这里我叫“海报”类:

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

//Create Twitter Client
var client = new TwitterClient(
                "x",
                "x",
                "x",
                "x"
            );

//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 = "myText"
    });

我的目标是使用“tweetItemshopImg”变量中的Id (开始时图像中的media.id),并将其赋予“TweetsV2Poster”类中的JSON属性。

jmo0nnb3

jmo0nnb31#

要生成documentation中所示的JSON示例:

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

修改TweetV2PostRequest,如下所示:

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
}

然后调用poster.PostTweet()如下:

//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 } }
    });

注意事项:

  • 似乎tweetinvi目前不支持使用Twitter V2 API发布带有关联媒体的tweets。BaseTweetsV2Parameters源代码的search出现了几个派生类型,比如GetTweetsV2Parameters,但没有PostTweetsV2Parameters
  • 为了确认生成了正确的JSON,我修改了TweetsV2Poster如下:
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"
          ]
       }
    }   
    """;

没有Assert,表明JSON与示例匹配(除了格式化)。

  • Tweetinvi没有记录它使用的JSON序列化器,但是它的nuget依赖于Newtonsoft.json,表明它是当前使用的序列化器。

相关问题