Skip to content

Instantly share code, notes, and snippets.

@Cloud-Awesome
Created May 26, 2022 13:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Cloud-Awesome/add4af38ca4bc512acd5022da47c36b4 to your computer and use it in GitHub Desktop.
Save Cloud-Awesome/add4af38ca4bc512acd5022da47c36b4 to your computer and use it in GitHub Desktop.
Most basic bot in MS Teams using an Outgoing Webhook to an Azure Function
public static class TeamsTester
{
[FunctionName("TeamsTester")]
public static async Task<IMessageActivity> RunAsync(
[HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)]
HttpRequest req, ILogger log)
{
// Get the activity passed through from the teams channel
var requestBody = await new StreamReader(req.Body).ReadToEndAsync();
var incomingActivity = JsonConvert.DeserializeObject<Activity>(requestBody);
// Remove the @BotName handle to get just the command passed through
const string pattern = @"<at>.*</at>";
const string replacement = "";
var command =
Regex.Replace(incomingActivity.Text, pattern, replacement, RegexOptions.IgnoreCase)
.Trim();
// Swtich through the command passed through to decide what to do and return to Teams
AdaptiveCard response = command.ToLower() switch
{
"sayhello" => SayHello(incomingActivity.From.Name),
"whoami" => WhoAmI(incomingActivity.From.Name, incomingActivity.From.AadObjectId),
_ => Help(command)
};
return new Activity
{
Attachments = new []
{
new Attachment()
{
ContentType = AdaptiveCard.ContentType,
Content = response
}
}
};
}
private static AdaptiveCard SayHello(string name)
{
var card = new AdaptiveCard(new AdaptiveSchemaVersion("1.4"))
{
Body = new List<AdaptiveElement>()
{
new AdaptiveTextBlock(){Text= $"Hello {name}!"}
}
};
return card;
}
private static AdaptiveCard WhoAmI(string name, string aadObjectId)
{
var card = new AdaptiveCard(new AdaptiveSchemaVersion("1.4"))
{
Body = new List<AdaptiveElement>()
{
new AdaptiveTextBlock(){Text= $"**Your name**: {name}"},
new AdaptiveTextBlock(){Text= $"**Your Azure AD ID**: {aadObjectId}"}
}
};
return card;
}
private static AdaptiveCard Help(string command)
{
var card = new AdaptiveCard(new AdaptiveSchemaVersion("1.4"))
{
Body = new List<AdaptiveElement>()
{
new AdaptiveTextBlock(){Text = $"You said {command}, which I didn't understand"},
new AdaptiveTextBlock(){Text = "The options available are:"},
new AdaptiveTextBlock(){Text = "**Say Hello**: This is a hello world example"},
new AdaptiveTextBlock(){Text = "**Who Am I**: This returns your name and Azure AD ID"}
}
};
return card;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment